我有一个名为%hash
的数组哈希$VAR1 = {
'reboot' => [
4442,
3483,
541
],
'prod-dev' => [
0,
485,
3421,
242,
425,
425,
484,
1,
244
]
};
如何添加每个键中的所有值并一次打印所有这些
reboot : sum
prod-dev : sum
谢谢欢呼
#!/usr/binkj/perl -w
use strict;
use warnings;
use List::Util qw( sum );
use Data::Dumper;
my ($substr, $new_line);
my @fields;
my %hash =();
open(my kj$logs, ">STDOUT") or die $!;
my ($total_sum, $total_t, $tsum);
my (@array, $key, $val);
while (<STDIN>) {
my @matches;
chomp;
next if $_ =~ m/still logged in/;
next if $_ =~ m/wtmp/;
next if $_ =~ m/\(-\d.+?\)/;
next if $_ =~ m/^$/g;
$_ =~ /(^.*?)\s.*?(\(.*?\))/g;
($key, $val) = ($1,$2);
$val =~ s/(\(|\))//g;
if($val =~ m/\d\+.*/){
$val =~ s/\+/\:/;
#$val =~ m/(^\d.)(:\d.:)(:\d.\s)/g;
my ($days, $hrs, $mins) = $val =~ /^(\d+):(\d+):(\d+).$/g;
$days = $days * 24 * 60;
$hrs = $hrs * 60;
$total_t = $days + $hrs + $mins;
#print $days . ":" . $hrs . ":" . $mins. "\n";
print "$total_t \n";
}else {
my ($hrs, $mins) = $val =~ /^(\d+):(\d+).$/g;
$hrs = $hrs * 60;
$total_t = $hrs + $mins;
print "$total_t \n";
}
push (@{$hash{$key}}, $total_t);
for my $k (keys(%hash)) {
printf("%-8s : %d\n", $k,sum( @{ $hash->{$k} } ),);
}
print Dumper (\%hash);
close $logs;
这是整个perl程序
我真的很难解决这个问题,我希望你们能帮助我答案 0 :(得分:4)
use List::Util qw( sum );
for my $k (keys(%$VAR1)) {
printf("%-8s : %d\n",
$k,
sum( @{ $VAR1->{$k} } ),
);
}
答案 1 :(得分:2)
根据问题并且没有任何外部模块,与上述答案有轻微但重要的区别。
foreach $val (keys(%$VAR1)){
$s=0;
foreach ( @{$VAR1->{$val}}){
$s = $_+$s;
}
print "$val :- $s ";
}
答案 2 :(得分:1)
我设法回答了这些人,非常感谢你!
foreach my $key ( keys %hash ) {
my $total_sum = 0;
foreach ( @{$hash{$key}} ) {
$total_sum += $_;
}
print $key . "" . $total_sum . "\n";
}
答案 3 :(得分:0)
来自sum
的List::Util
函数可用于总和:
#!/usr/bin/env perl
use strict;
use warnings;
my %hash = (
'reboot' => [ 4442, 3483, 541 ],
'prod-dev' => [ 0, 485, 3421, 242, 425, 425, 484, 1, 244 ],
);
use List::Util qw( sum );
my @sums;
for my $key ( keys %hash ) {
my $sum = sum @{ $hash{$key} };
push @sums, "$key: $sum\n";
}
print @sums;