Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^2: why use a hash instead of an array

by 5mi11er (Deacon)
on Jun 11, 2013 at 21:18 UTC ( #1038342=note: print w/ replies, xml ) Need Help??


in reply to Re: why use a hash instead of an array
in thread why use a hash instead of an array

For a person just learning perl, your example code is quite obtuse. You should at least attempt to explain how your code actually works.

I'd do it for you, but need to leave work now...

Update: since no one else has yet done so, and I'm back at work now, I'll try:

So, the $/ floating all over the above post is simply a special variable holding, by default, a "new line" character, ie. "\n". The first section

while(<DATA>){ chomp; $hash{$_}++ for split; }
simply reads in the data, and for every word in the DATA section, increments the hash table entry for that word. It would be more clear to beginners if it were written thusly:
while(<DATA>){ #get a line of text from the DATA area, put it in spec +ial variable $_ chomp; #remove the "new line" character from the $_ variable #create a word array from the $_ variable #split with no options splits on whitespace by default @words = split; foreach $word (@words) { $hash{$word}++; #increment the value pointed to by the $hash{ +$word} "key" } }
Once you have the data read in, you'll have the following data structure:
board => 1 chalk => 1 class => 2 desk => 1 professor => 1 school => 2 students => 2 table => 1 teacher => 3
2teez then uses more advanced perl to essentially do the following:
foreach $word (sort keys %hash) { print "$word\n"; } print "\n"; foreach $word (sort keys %hash) { if ($hash{$word} > 1) { print "$word\n"; } }
From these two beginner friendly examples, it should be pretty easy to do 2teez's 3rd challenge which is to print out the data structure I gave above.

-Scott


Comment on Re^2: why use a hash instead of an array
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (9)
As of 2014-12-25 03:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (159 votes), past polls