in reply to Summing column values

hi

well as Ratazong said this probably the easiest way to go and here is an example:

#!/usr/bin/perl use strict; #no warnings; open (IN, "<", $ARGV[0]) || die "$!"; my %hash; while (<IN>){ chomp; my @array =split(',',$_); my $id = substr $array[1], 1,3; (defined $hash{$array[0]}{$id}) ? ($hash{$array[0]}{$id} += $array[2 +]) : ($hash{$array[0]}{$id} = $array[2]) ; } close IN; foreach my $prim (keys %hash){ foreach my $sec (keys %{$hash{$prim}}){ print "$prim, $sec, $hash{$prim}{$sec}\n"; } }
hope this helps

baxy

Replies are listed 'Best First'.
Re^2: Summing column values
by BrowserUk (Patriarch) on Feb 24, 2010 at 10:25 UTC

    (defined $hash{$array[0]}{$id}) ? ($hash{$array[0]}{$id} += $array[2]) : ($hash{$array[0]}{$id} = $array[2]);

    That's more complicated than is necessary. Perl's clever enough to know that if you add a number to an undefined variable, to treat that var as 0. This would suffice:

    $hash{$array[0]}{$id} += $array[2];

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.