develooper Front page | perl.beginners | Postings from January 2011

Re: Newbie queries

Thread Previous | Thread Next
From:
dolphin
Date:
January 27, 2011 01:59
Subject:
Re: Newbie queries
Message ID:
bcf47663-e4ac-4e30-a07a-23f7d7fef331@i25g2000prd.googlegroups.com
On Jan 25, 6:43 pm, orasn...@gmail.com ("Octavian Rasnita") wrote:
> From: "dolphin" <yc282...@yahoo.com.sg>
>
>
>
>
>
>
>
>
>
> > Hi,
>
> > I'm learning perl now and would like to find out how to perform the
> > following if given in a text file?
>
> > AAAA,12
> > AAAA,437
> > BBBB,124
> > CCCC,45
> > BBBB,789
> > AAAA,67
> > CCC,567
> > DDD,5
>
> > How to sum up the 2nd column based on the 1st column with the
> > following result:
>
> > AAAA:
> > BBB:
> > CCC:
> > DDD:
>
> > Thanks in advance.
>
> You need to read the file line by line:
>
> use strict;
> use warnings;
>
> my %items;    #The hash with labels and their corresponding sums
>
> open my $file, '<', 'file_name' or die $!;
>
> while ( my $line = <$file> ) {
>
>     # Here split the line:
>     my ( $label, $value ) = split /,/, $line, 2;
>
>     # Then add each value for its corresponding label:
>     $items{$label} += $value;
>
> }
>
> close $file;
>
> # Here print the sorted hash of items:
> for my $label ( sort keys %items ) {
>     print "$label: $items{$label}\n";
>
> }
>
> HTH.
>
> Octavian

Hi,

Correct me that the "2" in the following means read?
:
my ( $label, $value ) = split /,/, $line, 2;


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About