Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: confused with summing certain elements from an array

by erroneousBollock (Curate)
on Nov 20, 2007 at 12:45 UTC ( #651913=note: print w/replies, xml ) Need Help??


in reply to confused with summing certain elements from an array

I want to make a hash contains as keys the unique elements from the @out and as values the sums of the letters from the @out1. Also I want the hash to be sorted
You can do this:

my %counts; while (my $key = shift @out) { $counts{$key} += shift @out1; }
That looks silly to me though... why would the data be in parallel arrays to begin with?

Also I want the hash to be sorted
Hashes aren't sorted.

You can iterate the keys of the hash in order as follows:

print "$_: \t$counts{$_}\n" for sort keys %counts;

-David

Replies are listed 'Best First'.
Re^2: confused with summing certain elements from an array
by GrandFather (Sage) on Nov 20, 2007 at 19:56 UTC

    The data are in parallel arrays because that is how the designer of the homework specified the problem. ;)

    Perl offers several ways of managing data in that fashion and I expect there may be discussion of the pros and cons of each following the submission of answers. I'd hope too that your point is made - that is not a Perlish way to manage data in most cases.


    Perl is environmentally friendly - it saves trees

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://651913]
help
Chatterbox?
[marto]: hey Corion, good weekend?
[Corion]: marto: Yeah, even though I didn't write any code :)
[Corion]: But at least I have a plan of action to move the site to https, played some (free!) VR games with friends and watched the plans for the next German Perl workshop progress ;)

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (10)
As of 2017-08-21 09:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Who is your favorite scientist and why?



























    Results (319 votes). Check out past polls.

    Notices?