cterra cterra - 3 months ago 9
Perl Question

Get all values from one dimension in a Perl hash

I have a hash built like this:

my %datavalue2;

foreach my $alert ( @{ $data } ) {

my @date = split(/ /,$alert->{logged});

$status = $alert->{status}->{status};
$type = $alert->{type};

if ( ! defined $datavalue2{$date[0]}{$type}{$status} ) {
# print "initialisation de la variable du ".$date[0]." de type ".$type." avec le status ".$status."<br>";
$datavalue2{$date[0]}{$type}{$status}=1;
}
else {
# print "incr&eacute;mentation de la variable du ".$date[0]." de type ".$type." avec le status ".$status."<br>";
$datavalue2{$date[0]}{$type}{$status} +=1;
}

# print "<br> ";
}


How can I get the sum of all
$status=1
for one date and each type?

I want something like
$total_type1 += $datavalue2{2016-08-15}{*}{1}
but I don't know the syntax. Is it possible?

Answer

You have to sum up the values for each type. Either you do it with the existing loop

my %datavalue2;
my %totalsPerStatus;
foreach my $alert ( @{ $data } )
{
   ...
   $totalsPerStatus{$date[0]}{$status} //= 0; # initialize total per status
   $totalsPerStatus{$date[0]}{$status}++; # increment total
}

$total_type1 += $totalsPerStatus{'2016-08-15'}{1};

... or afterwards ...

sub getTotalPerStatus {
    my ($datavalue2, $date, $status) = @_;

    $total = 0;
    foreach my $type (keys %{$datavalue2->{$date}}) {
        if (exists $datavalue2->{$date}->{$type}->{$status}) {
            $total += $datavalue2->{$date}->{$type}->{$status} 
        }
    }
    return $total;
}

$total_type1 += getTotalPerStatus(\%datavalue2, '2016-08-15', 1);
Comments