Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: why use a hash instead of an array

by Preceptor (Deacon)
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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1038328]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2018-02-20 21:59 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (274 votes). Check out past polls.