Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: why use a hash instead of an array

by Preceptor (Chaplain)
on Jun 11, 2013 at 19:08 UTC ( #1038328=note: print w/ replies, xml ) Need Help??


in reply to why use a hash instead of an array

So you've set up a bunch of variables, that act as references to elements of an array? You could do that, but ... what advantage do you gain by doing so?

I really wouldn't worry about efficiency - algorithm design is far more relevant than use of arrays vs. hashes.

Otherwise? Well, hashes are just a much simpler idiom to use - clearer code is more valuable than squeezing out miniscule performance advantages.

A lot of data _is_ structured as key/value pairs, and being able to manipulate it trivially is an advantage.

For example - given a list of words (one perl line for simplicity) count occurences.

With a hash:

foreach my $word ( <STDIN> ) { $word_list{$word}++; } foreach my $word ( keys %word_list ) { print "$word : $word_list{$word}\n"; }
You don't need to completely swap hashes for lists, but personally I'd suggest that any time you're using array indicies, you're probably doing something wrong, and making your code less readable.

foreach my $element ( @list_of_stuff ) { print $element,"\n"; }
Is a very useful idiom.


Comment on Re: 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://1038328]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2014-08-31 07:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls