简体   繁体   English

循环遍历hash-perl中的数组

[英]Looping through array that's inside hash - perl

Am I doing this right? 我这样做了吗?

my $variable = "hello,world";

my @somearray = split(',',$variable);

my %hash = ( 'somevalue' => @somearray);

foreach my $key ( keys %hash ) {
    print $key;
    foreach my $value ( @{$hash{$key}} ) {
        print $value; #the value is not being read/printed
    }
}

I don't know if I'm accessing the array that is stored in the hash for the particular value 我不知道我是否正在访问存储在特定值的哈希中的数组

You've been bitten by perl's flattening nature of lists. 你已经被perl的扁平化列表所困扰了。 You see, when you do: my %hash = ('somekey' => @somearray) , perl converts that into a list form of hash assignment. 你看,当你这样做: my %hash = ('somekey' => @somearray) ,perl会将其转换为哈希赋值的列表形式。 So, what perl actually sees is: 那么,perl实际看到的是:

my %hash = ('somekey' => 'hello', 'world' => ''); # I have put '' for simplicity, though it might well be `undef`

So, the next time you look up by 'somekey', you end up getting the string 'hello' and not the array "['hello', 'world']" 所以,下次你用'somekey'查找时,你最终会得到字符串'hello'而不是数组“['hello','world']”

To fix this, you can use references. 要解决此问题,您可以使用引用。 perlref can help you there for more information. perlref可以帮助您获得更多信息。

my %hash = ('somekey' => \@somearray);
# $hash{'somekey'} is an array reference now.
# So you use the pointy lookup syntax. 
print $hash{'somekey'}->[0]; 

Another useful tool in visualising data structures is using the module Data::Dumper . 可视化数据结构的另一个有用工具是使用模块Data::Dumper It's available in the perl core distribution. 它可以在perl核心发行版中使用。 Using it is as simple as doing: 使用它就像做:

use Data::Dumper;

print Dumper \%hash; # remember to pass in a reference to the actual datastructure, not the data structure itself.

Have fun! 玩得开心!

This is wrong: 这是错的:

my %hash = ( 'somevalue' => @somearray);

The array is "flattened" to a list, so the line is equivalent to 该数组被“展平”为一个列表,因此该行相当于

my %hash = qw( somevalue hello world );

You need an array reference to create the inner array: 您需要一个数组引用来创建内部数组:

my %hash = ( 'somevalue' => \@somearray);

So you wanted to create a hash of array data structure. 所以你想创建一个数组数据结构的哈希。 Something like this will also work. 像这样的东西也会起作用。

my $variable = "hello,world";

my @somearray = split(',',$variable);

my %hash;
#my %hash = ( 'somevalue' => @somearray);
push (@{$hash{'somevalue'}},@somearray);  #Storing it in a hash of array

foreach my $key ( keys %hash ) {
    print $key;
    foreach my $value ( @{$hash{$key}} ) {
        print $value; #the value is not being read/printed
    }
}

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

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