在Perl中用hashreference替换哈希?

在Perl中用hashreference替换哈希?,perl,Perl,我有一个子例程,它获取一个hashreference作为参数。 我可以通过引用操作单个哈希值。 我想替换引用点所在的整个散列,以便在该散列引用的任何地方都可以看到更改 sub replace{ my $hashref = shift; # can manipulate hash here $hashref->{key} = "newValue"; # how to replace replace the hash here by a new hash

我有一个子例程,它获取一个hashreference作为参数。

我可以通过引用操作单个哈希值。 我想替换引用点所在的整个散列,以便在该散列引用的任何地方都可以看到更改

sub replace{
    my $hashref = shift;

    # can manipulate hash here
    $hashref->{key} = "newValue";

    # how to replace replace the hash here by a new hash
    $newHashRef = {
        key  => "value",
        key2 => "value2",
    };
}
可能吗

%$hashref = (
    key => "value",
    key2 => "value2",
);

%$hashref
表示“引用的哈希值,
$hashref
”,分配给该哈希值将替换其内容,就像不涉及引用一样。

只需分配给未引用的哈希值:

my $hashref = shift;
%$hashref = ();
sub replace{
    my $hashref = shift;
    %$hashref = ( key1 => "value1", key2 => "value2" );
}

要替换引用哈希的内容,请执行以下操作:

my $hashref = shift;
%$hashref = ();
sub replace{
    my $hashref = shift;
    %$hashref = ( key1 => "value1", key2 => "value2" );
}
(如果hash是
%hash
,hash ref是
%{$hashref}
,简称
%$hashref

要替换引用本身,请执行以下操作:

sub replace{
    $_[0] = { key1 => "value1", key2 => "value2" };
}