我有一大堆哈希,我想从数组中获取一些哈希并插入新数组而不更改第一个数组.我有问题将哈希推送到数组,如何访问作为哈希的第i个元素.
my @myarray; $my_hash->{firstname} = "firstname"; $my_hash->{lastname} = "lastname"; $my_hash->{age} = "25"; $my_hash->{location} = "WI"; push @myarray,$my_hash; $my_hash->{firstname} = "Lily"; $my_hash->{lastname} = "Bily"; $my_hash->{age} = "22"; $my_hash->{location} = "CA"; push @myarray,$my_hash; $my_hash->{firstname} = "something"; $my_hash->{lastname} = "otherthing"; $my_hash->{age} = "22"; $my_hash->{location} = "NY"; push @myarray,$my_hash; my @modifymyhash; for (my $i=0;$i<2; $i++) { print "No ".$i."\n"; push (@modifymyhash,$myarray[$i]); print "".$myarray[$i]."\n"; #How do I print first ith element of array which is hash. }
解决方法
首先你应该
use strict; use warnings;
然后定义
my $my_hash;
在分配值之前初始化$my_hash,否则您将覆盖它,并且所有三个元素都指向相同的哈希
$my_hash = {};
最后,访问哈希的成员
$myarray[$i]->{firstname}
或者要打印整个哈希,例如可以使用Data::Dumper
print Dumper($myarray[$i])."\n";
或其他一些方法,How can I print the contents of a hash in Perl?或How do I print a hash structure in Perl?
更新您的评论:
你复制哈希
push (@modifymyhash,$myarray[$i]);
进入新阵列,完美运作.你可以验证
foreach my $h (@myarray) { print Dumper($h),"\n"; } foreach my $h (@modifymyhash) { print Dumper($h),"\n"; }
这两个数组都有相同的哈希值.
如果要创建深层副本,而不仅仅是引用,则可以分配新哈希并将第i个元素复制到副本中.然后将副本存储在@modifymyhash中
my $copy = {}; %{$copy} = %{$myarray[$i]}; push (@modifymyhash,$copy);