Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: using hashes

by kennethk (Monsignor)
on Sep 26, 2013 at 15:06 UTC ( #1055853=note: print w/ replies, xml ) Need Help??


in reply to iterating hash keys?

First, what mtmcc said.

Second, a quote from the illustrious prophet: Doing linear scans over an associative array is like trying to club someone to death with a loaded Uzi. -- TimToady

You should put your keys into a hash, yes, but then just iterate over your array. The array values are exactly what you need to access the hash values. So it might look like:

my %id = (bananas => 456, oranges => 23, peaches => 897236, kiwis => 3726, ); my @replaces = ('kiwis','oranges','bananas','bananas'); for my $i (0 .. $#replaces) { $replaces[$i] = $id{$replaces[$i]}; }
If I were going to actually write this, I'd take advantage of the fact that the loop iterator for Foreach Loops is an lvalue for the array element ($_ = $id{$_} for @replaces;), but that might be a little to magical for your taste given your familiarity with the language.

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.


Comment on Re: using hashes
Select or Download Code
Re^2: using hashes
by R56 (Acolyte) on Sep 26, 2013 at 15:53 UTC

    Thanks Kenneth, I understand your code, but I may have more than one name in the same line, such as:

    bananas,peaches,kiwis

    peaches,peaches

    pineapple

    (...)

    So we couldn't use that kind of cycling on the array positions, right? Or am I missing something?

      ... am I missing something?

      You're missing what BrowserUk said here, an approach that processes an entire line at a time.

      The next part to think about is what happens if you encounter a 'word' in a line that doesn't exist in your translation hash, e.g., the line
          "peaches,peaches,foobar,kiwis\n"
      (hints: exists, next, maybe  // (defined-or) or  ?: (ternary/conditional operator) – see perlop for the latter two).

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (11)
As of 2014-10-24 10:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (131 votes), past polls