Perl 数组值通过每个唯一键进行访问和求和
# my code as follows
use strict;
use FileHandle;
my @LISTS = ('incoming');
my $WORK ="c:\";
my $OUT ="c:\";
foreach my $list (@LISTS) {
my $INFILE = $WORK."test.dat";
my $OUTFILE = $OUT."TEST.dat";
while (<$input>) {
chomp;
my($f1,$f2,$f3,$f4,$f5,$f6,$f7) = split(/\|/);
push @sum, $f4,$f7;
}
}
while (@sum) {
my ($key,$value)= {shift@sum, shift@sum};
$hash{$key}=0;
$hash{$key} += $value;
}
while my $key (@sum) {
print $output2 sprintf("$key1\n");
# print $output2 sprintf("$key ===> $hash{$key}\n");
}
close($input);
close($output);
我收到错误添加时未初始化错误 (+) 如果我使用第二次打印 如果我使用第一次打印,我会得到 HASH(0x19a69451) 值。 我请求您纠正我。
我的输出应该是
unique Id ===> Total Revenue ($f4==>$f7)
# my code as follows
use strict;
use FileHandle;
my @LISTS = ('incoming');
my $WORK ="c:\";
my $OUT ="c:\";
foreach my $list (@LISTS) {
my $INFILE = $WORK."test.dat";
my $OUTFILE = $OUT."TEST.dat";
while (<$input>) {
chomp;
my($f1,$f2,$f3,$f4,$f5,$f6,$f7) = split(/\|/);
push @sum, $f4,$f7;
}
}
while (@sum) {
my ($key,$value)= {shift@sum, shift@sum};
$hash{$key}=0;
$hash{$key} += $value;
}
while my $key (@sum) {
print $output2 sprintf("$key1\n");
# print $output2 sprintf("$key ===> $hash{$key}\n");
}
close($input);
close($output);
I am getting errors Unintialized error at addition (+) If I use 2nd print
I get HASH(0x19a69451) values if I use 1st Print.
I request you please correct me.
My output should be
unique Id ===> Total Revenue ($f4==>$f7)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是错误的:
Perl 将其读取为以
c:";\n...
开头的字符串。或者换句话说,它是一个失控的字符串。您需要将最后一个字符写为 < code>\\ 以转义\
并防止其转义后续的"
字符This is wrong:
Perl reads that as a string starting with
c:";\n...
. Or in other words, it is a run away string. You need to write the last character as\\
to escape the\
and prevent it from escaping the subsequent"
character您可能想使用括号而不是大括号:
如果
@sum
数组包含奇数个元素,您将收到Unintialized error ataddition (+)
警告。另请参阅 perltidy。
You probably want to use parens instead of braces:
You would get that
Unintialized error at addition (+)
warning if the@sum
array has an odd number of elements.See also perltidy.
您不应输入第二个 while 循环:
因为前一个循环将数组
@sum
留空。您可以更改为:
You should not enter the second while loop :
because the previous one left the array
@sum
empty.You could change to: