Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Re: Re: Help on array element counting

by monktim (Friar)
on Oct 27, 2003 at 19:45 UTC ( #302493=note: print w/replies, xml ) Need Help??


in reply to Re: Re: Help on array element counting
in thread Help on array element counting

# Declare a hash named fruits. A hash contains # { key,value } pairs where the key fields are unique. my %fruits; # Get each element in the @fruits array and assign it to #the { key } portion of the hash. Also, increment the #{ value } part of the hash (the value starts with 0). #This will count the number of times the { key } appears in #the array $fruits{$_}++ for ( @fruits ); #Declare variables for { key, value } my ( $fruit, $count ); #Get each { key, value } pair and assign them to #{ fruit, count } for ( $fruit, $count ) ( each %fruits ) { #Print out the number of times the fruit existed. print "$fruit => $count\n"; }

Replies are listed 'Best First'.
Re: Re: Re: Re: Help on array element counting
by Art_XIV (Hermit) on Oct 27, 2003 at 20:40 UTC

    This is a more 'perl baby-talk' version of monktim's code, in which he exploits several perl idioms which you may not be familiar with (yet!):

    my %fruit_counts; foreach my $fruit(@fruit_list) { $fruit_counts{$fruit} = $fruit_counts{$fruit} + 1; #lhand for '++' } foreach my $fruit(keys %fruit_counts) { print "$fruit => ", $fruit_counts{$fruit}, "\n"; }

    This is one of the neatest things about Perl! monktim's code and mine look very different but are very similar in an elemental sense.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://302493]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2022-08-10 18:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?