简体   繁体   English

如何在perl中访问哈希数组?

[英]How do I access array of hash in perl?

I have a big array of hashes, I want to grab some hash from the array and insert into new array without changing the first array. 我有一大堆哈希,我想从数组中获取一些哈希并插入新数组而不更改第一个数组。 I am having problem pushing the hash to array, how do I access the ith element which is a hash. 我有问题将哈希推送到数组,如何访问作为哈希的第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.
 }

First you should 首先你应该

use strict;
use warnings;

then define 然后定义

my $my_hash;

initialize $my_hash before you assign values, because otherwise you overwrite it and all three elements point to the same hash 在分配值之前初始化$my_hash ,否则您将覆盖它,并且所有三个元素都指向相同的哈希

$my_hash = {};

and finally, to access the hash's members 最后,访问哈希的成员

$myarray[$i]->{firstname}

or to print the whole hash, you can use Data::Dumper for example 或者要打印整个哈希,您可以使用Data :: Dumper作为示例

print Dumper($myarray[$i])."\n";

or some other method, How can I print the contents of a hash in Perl? 或者其他一些方法, 如何在Perl中打印哈希的内容? or How do I print a hash structure in Perl? 或者如何在Perl中打印哈希结构?

Update to your comment: 更新您的评论:

You copy the hashes with 你复制哈希

push (@modifymyhash, $myarray[$i]);

into the new array, which works perfectly. 进入新阵列,完美运作。 You can verify with 你可以验证

foreach my $h (@myarray) {
    print Dumper($h), "\n";
}

foreach my $h (@modifymyhash) {
    print Dumper($h), "\n";
}

that both arrays have the same hashes. 这两个数组都有相同的哈希值。

If you want to make a deep copy, instead of just the references, you can allocate a new hash and copy the ith element into the copy. 如果要创建深层副本,而不仅仅是引用,则可以分配新哈希并将第ith元素复制到副本中。 Then store the copy in @modifymyhash 然后将副本存储在@modifymyhash

my $copy = {};
%{$copy} = %{$myarray[$i]};
push (@modifymyhash, $copy);

To dereference a hash, use %{ ... } : 要取消引用哈希,请使用%{ ... }

print  %{ $myarray[$i] }, "\n";

This probably still does not do what you want. 这可能仍然没有做你想要的。 To print a hash nicely, you have to iterate over it, there is no "nice" stringification: 要很好地打印哈希,你必须迭代它,没有“漂亮”的字符串化:

print $_, ':', $myarray[$i]{$_}, "\n" for keys %{ $myarray[$i] };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM