CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Do not understand what line 4 and 5 does. Please help!

 



yoplocheo
Novice

Jan 7, 2016, 12:35 AM

Post #1 of 2 (1203 views)
Do not understand what line 4 and 5 does. Please help! Can't Post


Code
use warnings; 
my %dup=(); #creates empty hash
my @colours=qw(red blue red green yellow green red orange);
foreach my $color (@colours){
$dup{$color} = $dup{$color}+1;
}
printf "Color\tNumber of occurences\n";
while((my $key, my $value)=each %dup){
printf "%-12s%-s\n", $key, $value;
}
@colours = sort keys %dup;
print "Duplicates removed: @colours\n";

Can someone provide an indept explanation on whats going on on line 4 and 5:

Code
foreach my $color (@colours){ 
$dup{$color} = $dup{$color}+1;



(This post was edited by yoplocheo on Jan 7, 2016, 12:36 AM)


Laurent_R
Veteran / Moderator

Jan 7, 2016, 6:39 AM

Post #2 of 2 (1187 views)
Re: [yoplocheo] Do not understand what line 4 and 5 does. Please help! [In reply to] Can't Post

It is populating the %dup color hash with the number of times each color appears in the @colours array. At the end, you should have this structure:


Code
0  HASH(0x6005dcab0) 
'blue' => 1
'green' => 2
'orange' => 1
'red' => 3
'yellow' => 1


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives