in reply to find unique elments and sum the corresponding values

Your request would be clearer, if you had used code tags. see How do I post a question effectively?.

My suggestion:

#! /usr/bin/perl -l use strict; use warnings; my %sum_of; # read linewise from filehandle while ( my $line = <DATA> ) { # remove linebreak; for details, see: perldoc -f chomp chomp $line; # split at whitespace characters; see: perldoc -f split # change \s to \t if only tabs are allowed; # remove + from pattern, if only one whitespace separates the column +s my ( $name, @fields ) = split m{\s+}, $line; # support multiple columns; sum up the fields per column for my $idx ( 0 .. $#fields ) { # create a Hash of Arrays and store the sums; see: perldoc perldsc $sum_of{ $name }->[$idx] += $fields[$idx]; } } # print result for my $name ( keys %sum_of ) { print join "\t", $name, @{ $sum_of{$name} }; } # __DATA__ AA 12 bb 34 AA 76 cc 98 dd 76 bb 98

update

Replies are listed 'Best First'.
Re^2: find unique elments and sum the corresponding values
by Prl_learner (Initiate) on Feb 11, 2009 at 23:36 UTC
    Hi..many thanks for the reply, I couldn't understand the main part of the script, the while loop. However, when I exscuted the script I got this message: Global symbol "$sum_of" requires explicit package name at SortSum.Pl line 22. Execution of SortSum.Pl aborted due to compilation errors How can this be fixed? and if possible can you explain the script to me so I can learn? thanks

      You really need to spend some time reading documentation. If you haven't a copy of 'Learning Perl' you should at least read through the Getting Started with Perl section in Tutorials.


      True laziness is hard work

      Don't know if you already saw my updated code. I added some comments and fixed that syntax error. Had a bad typo in the "print result" section.

        Hey linuxer, Yes I saw, studied, and used it. Thank you so much.