Perl 哈希数组 - 引用数组中的每个哈希?
我正在尝试创建一个哈希数组,我想知道如何引用数组中的每个哈希?
例如:
while(<INFILE>)
{
my $row = $_;
chomp $row;
my @cols = split(/\t/,$row);
my $key = $cols[0]."\t".$cols[1];
my @total = (); ## This is my array of hashes - wrong syntax???
for($i=2;$i<@cols;$i++)
{
$total[$c++]{$key} += $cols[$i];
}
}
close INFILE;
foreach (sort keys %total) #sort keys for one of the hashes within the array - wrong syntax???
{
print $_."\t".$total[0]{$_}."\n";
}
提前感谢您的帮助。
I am trying to create an array of hashes, and I am wondering how to reference each hash within the array?
For eg:
while(<INFILE>)
{
my $row = $_;
chomp $row;
my @cols = split(/\t/,$row);
my $key = $cols[0]."\t".$cols[1];
my @total = (); ## This is my array of hashes - wrong syntax???
for($i=2;$i<@cols;$i++)
{
$total[$c++]{$key} += $cols[$i];
}
}
close INFILE;
foreach (sort keys %total) #sort keys for one of the hashes within the array - wrong syntax???
{
print $_."\t".$total[0]{$_}."\n";
}
Thanks in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不需要
This:
足以满足你的需求。不需要特殊的语法来声明您的数组将包含哈希值。
可能有不同的方法来执行
foreach
部分,但这应该有效:[顺便说一句,在该循环内声明
my @total;
可能不是您想要的(这将是每行重置)。将其移到第一个循环之外。]并且
use strict;使用警告;
,显然:-)You don't need
This:
is sufficient for what you are after. No special syntax needed to declare that your array will contain hashes.
There's probably different ways of doing the
foreach
part, but this should work:[BTW, declaring
my @total;
inside that loop is probably not what you want (it would be reset on each line). Move that outside the first loop.]And
use strict; use warnings;
, obviously :-)这是我得到的:
我只是迭代
@total
,并为每个 hashref 按排序顺序获取一个 slice 并用制表符连接这些值。如果您不需要按排序顺序排列它们,则可以
但是我也会像这样压缩行处理:
但是使用
List::MoreUtils
,你也可以这样做:Here's what I get:
I'm simply iterating through
@total
and for each hashref taking a slice in sorted order and joining those values with tabs.If you didn't need them in sorted order, you could just
But I also would compress the line processing like so:
But with
List::MoreUtils
, you could also do this: