Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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?

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2015-10-07 21:52 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (201 votes), past polls