era*_*ran 4 perl perl-data-structures
对不起这个语法问题.我找不到解决办法.我想在perl中有一个哈希数组,每个哈希都有字符串和数组.我正在尝试编写以下代码:
use strict;
my @arr = (
{ name => "aaa" , values => ("a1","a2") },
{ name => "bbb" , values => ("b1","b2","b3") }
);
foreach $a (@arr) {
my @cur_values = @{$a->{values}};
print("values of $a->{name} = @cur_values\n");
};
Run Code Online (Sandbox Code Playgroud)
但这对我不起作用.我收到编译错误和警告(使用perl -w)
a.pl第2行的匿名哈希中奇数个元素.在a.pl第9行使用"strict refs"时,不能使用字符串("a1")作为ARRAY引用.
我想在perl中有一个哈希数组
你不能.数组只包含Perl中的标量.但是,{}会创建一个hashref,这是一个标量并且很好.
但是这个:
{ name => "aaa" , values => ("a1","a2") }
Run Code Online (Sandbox Code Playgroud)
意思是:
{ name => "aaa" , values => "a1", "a2" },
Run Code Online (Sandbox Code Playgroud)
你想要一个arrayref(它是一个标量),而不是一个值的列表.
{ name => "aaa" , values => ["a1","a2"] }
Run Code Online (Sandbox Code Playgroud)
请尝试以下方法:
use strict;
my @arr = (
{ name => "aaa" , values => ["a1","a2"] },
{ name => "bbb" , values => ["b1","b2","b3"] }
);
foreach $a (@arr) {
my @cur_values = @{$a->{values}};
print("values of $a->{name}: ");
foreach $b (@cur_values){
print $b . ", "
}
print "\n";
};
Run Code Online (Sandbox Code Playgroud)
在第3行和第4行定义数组时,您只需使用方括号.