max210 has asked for the wisdom of the Perl Monks concerning the following question:

Hello All,
I have stored time stamp for messages coming to my system in hash and I need to count how many came for each minute. Logic is pretty simple but 2Darray is storing values where I dont want to??
my $key1=0; my $val1=0; my @count_message = (); my %msg_rate = ('1', '00:00:00,284', '2', '00:00:00,462', '3', '01:01: +00,462', '4', '00:02:00,462', '5', '01:03:00,462'); while( ($key1, $val1) = each(%msg_rate) ) { my ($hh1,$mm1,$ssms1) = split(/\:/,$val1); $count_message[$hh1,$mm1]++; print "countmsg $hh1 $mm1 = $count_message[($hh1,$mm1)]\n"; } print "Wrong Values: $count_message[(1,0)]\n"; print "Wrong Values: $count_message[(0,3)]\n"; print "Wrong Values: $count_message[(0,1)]\n"; print "Wrong Values: $count_message[(1,2)]\n";

Replies are listed 'Best First'.
Re: Count Messages for each minute, 2D array error
by FunkyMonk (Bishop) on Apr 03, 2008 at 21:52 UTC
    Had you been using strict & warnings, perl would have informed you that "Multidimensional syntax $count_message[$hh1,$mm1] not supported".

    In Perl multidimensional arrays (aka array of arrayrefs) are written:

    $count_message[$hh1][$mm1]++;

    However, I think you'd be better off using hashes:

    use Data::Dumper; my %msg_rate = ('1', '00:00:00,284', '2', '00:00:00,462', '3', '01:01: +00,462', '4', '00:02:00,462', +'5', '01:03:00,462'); my %count_per_min; while( my ($key1, $val1) = each(%msg_rate) ) { my ($hh1,$mm1,$ssms1) = split(/\:/,$val1); $count_per_min{"$hh1:$mm1"}++ } print Dumper \%count_per_min;

    Output:

    $VAR1 = { '00:00' => 2, '00:02' => 1, '01:03' => 1, '01:01' => 1 };
Re: Count Messages for each minute, 2D array error
by ikegami (Patriarch) on Apr 03, 2008 at 21:55 UTC

    The short answer: $count_message[$hh1][$mm1]

    The long answer: There's no such thing as a 2d array in Perl. However, you can store references to arrays (including references to anonymous arrays) in arrays, effectively creating a 2d array.

    $a[$i][$j]
    is short for
    $a[$i]->[$j]
    which, thanks to autovivification, is short for something like
    $a[$i] ||= []; $a[$i]->[$j]

    See perllol

    That said, you might be better off with a hash keyed on "hh:mm" rather than an array. I also avoid each since it prevents the use of last and die.