http://www.perlmonks.org?node_id=1192509


in reply to array of arrays

This can be done using a hash.
#!/usr/bin/env perl use strict; use warnings; open my $fh, '<', 'test_file.txt' or die 'Can not open file'; my %data; while(<$fh>){ chomp $_; my ($key, $val) = split(/\|/, $_); $data{$key} += $val; } foreach my $key ( sort { $a <=> $b } keys %data ){ print "the total is: (".$data{$key}.")\n"; } exit;

Replies are listed 'Best First'.
Re^2: array of arrays
by Anonymous Monk on Jun 12, 2017 at 22:43 UTC

    Hello kevbot:

    Thank you for your solution. Since this task is for me to learn, took me a while to study one by one from the bottom up. Yours was the last.

    I would like to know if it is possible for you to show me how print on the fly each row of the while loop with the array size and the sum total of each array.

    Something like this:

    my %data; $e = '0'; while(<$fh>){ $e++; chomp $_; my ($key, $val) = split(/\|/, $_); push @{$data{$key}},$val; $Grand_Total += "$val"; my $size = scalar(@{$data{$key}}); ## WRONG doesn't print $Sub_Total[$key] += $data{$key}[$val]; ## WRONG doesn't prin +t print"Row ($e) / Array Size [$size] key ($key) / Amount ($val +) / Sub Total ($Sub_Total[$key]) / Grand_Total = ($Grand_Total)<hr>" +; }


    Hope you can do it

    Thanx
    virtualweb

      Replace

      $Sub_Total[$key] += $data{$key}[$val];
      with
      $Sub_Total[$key] +=$val;
      You should then come back and tell us what you did wrong in the original.

      Hello virtualweb,

      My solution did not use an array. The contents of $data{$key} are a single scalar value (the running total of values for the given key). So, my code is not keeping track of how many data entries that are encountered for a given value of $key.

      Here is a modified version of my code that will print out the information you request. Note, I'm still not using arrays. In this code, $data{$key} contains a hash reference with keys size and total. The value of size is the current number of elements found for the given $key. The value of total is the current total of values that have been encountered for the given $key.

      #!/usr/bin/env perl use strict; use warnings; open my $fh, '<', 'test_file.txt' or die 'Can not open file'; my %data; my $row_number = 1; my $grand_total = 0; while(<$fh>){ chomp $_; my ($key, $val) = split(/\|/, $_); $data{$key}->{'size'}++; $data{$key}->{'total'} += $val; $grand_total += $val; print "Row ($row_number) ". "/ Array Size [$data{$key}->{'size'}] key ($key) ". "/ Amount ($val) / Sub Total ($data{$key}->{'total'}) ". "/ Grand_Total = ($grand_total)\n"; ++$row_number; } foreach my $key ( sort { $a <=> $b } keys %data ){ print "the total is: (".$data{$key}->{'total'}.")\n"; } exit;