使用单个哈希的副本填充perl哈希数组

Ste*_*han 0 perl copy reference perl-data-structures

我搜索并搜索过,但我找不到任何我发现的代码.我很抱歉,如果这是重复旧的,但我现在花了2天试图让这10行工作,我在我的智慧结束没有留下头发:-(

我正在运行Perl 5.8.8.

我想在Perl中填充哈希数组,使其包含我正在更新的单个哈希变量的多个副本.我的代码在这里:

use strict;
use warnings;

my @array;

my %tempHash = (state => "apple", symbol => "54", memberId => "12345");
push(@array, \%tempHash);

%tempHash = (state => "tiger", symbol => "22", memberId => "12345");
push(@array, \%tempHash);

%tempHash = (state => "table", symbol => "37", memberId => "12345");
push(@array, \%tempHash);

printf("%p %p %p\n", $array[0], $array[1], $array[2]);

foreach my $entry (@array){
    printf("state: %s\n", $entry->{state});
    printf("memberId: %s\n", $entry->{memberId});
    printf("symbol: %s\n\n", $entry->{symbol});
}
Run Code Online (Sandbox Code Playgroud)

这会产生以下输出:

1868954 18688d0 18688c4
state: table
memberId: 12345
symbol: 37

state: table
memberId: 12345
symbol: 37

state: table
memberId: 12345
symbol: 37
Run Code Online (Sandbox Code Playgroud)

所以在我看来,数组中的标量值是不同的.然而,这些标量指向的散列中的值是完全相同的.

在此先感谢您的帮助.

Dal*_*aen 6

1)你发布的代码不起作用use strict;,你的意思是%tempHash和%hash真的是同一个变量吗?

2)如果你使用%s而不是%p,你将得到3个相同的HASH(0x1234abcd)字符串,这意味着数组的内容确实引用了相同的哈希.

3)我建议每次都创建一个新的匿名哈希:

#!/usr/bin/perl -w
use strict;
use Data::Dumper;

my @array;
my %tempHash = (state => "apple", symbol => "54",memberId => "12345");
push(@array, { %tempHash });

%tempHash = (state => "tiger", symbol => "22", memberId => "12345");
push(@array, { %tempHash });

%tempHash = (state => "table", symbol => "37", memberId => "12345");
push(@array, { %tempHash });

print Dumper( \@array );
Run Code Online (Sandbox Code Playgroud)