Perl哈希参考

示例

哈希引用是标量,它包含一个指向包含哈希数据的内存位置的指针。因为标量直接指向散列本身,所以当将其传递给子例程时,对散列所做的更改并不像常规散列一样在子例程中是局部的,而是全局的。

首先,让我们检查一下将常规哈希传递给子例程并在其中进行修改时会发生什么:

use strict;
use warnings;
use Data::Dumper;

sub modify
{
    my %hash = @_;

    $hash{new_value} = 2;

    print Dumper("Within the subroutine");
    print Dumper(\%hash);

    return;
}

my %example_hash = (
    old_value   => 1,
);

modify(%example_hash);

print Dumper("After exiting the subroutine");
print Dumper(\%example_hash);

结果是:

$VAR1 = 'Within the subroutine';
$VAR1 = {
          'new_value' => 2,
          'old_value' => 1
        };
$VAR1 = 'After exiting the subroutine';
$VAR1 = {
          'old_value' => 1
        };

注意,退出子程序后,哈希值保持不变。对它的所有更改都在Modify子例程中进行,因为我们传递了哈希的副本,而不是哈希本身。

相比之下,传递hashref时,会将地址传递给原始哈希,因此在子例程中进行的任何更改都将对原始哈希进行:

use strict;
use warnings;
use Data::Dumper;

sub modify
{
    my $hashref = shift;

    # De-reference the hash to add a new value
    $hashref->{new_value} = 2;

    print Dumper("Within the subroutine");
    print Dumper($hashref);

    return;
}

# Create a hashref
my $example_ref = {
    old_value   => 1,
};

# Pass a hashref to a subroutine
modify($example_ref);

print Dumper("After exiting the subroutine");
print Dumper($example_ref);

这将导致:

$VAR1 = 'Within the subroutine';
$VAR1 = {
          'new_value' => 2,
          'old_value' => 1
        };
$VAR1 = 'After exiting the subroutine';
$VAR1 = {
          'new_value' => 2,
          'old_value' => 1
        };