http://www.perlmonks.org?node_id=1055864


in reply to Re: using hashes
in thread iterating hash keys?

Thanks for the help Browser, but apparently I'm way behind in Perl knowledge yet, as I don't really get the code... That's how I know I'm overcomplicating something that is really simple :|

Is the $1 var pointing to the value of the hash?

Replies are listed 'Best First'.
Re^3: using hashes
by BrowserUk (Patriarch) on Sep 26, 2013 at 17:09 UTC
    Is the $1 var pointing to the value of the hash?

    $1 captures the words in the string one at a time. This $hash{ $1 } looks that word up in the hash and returns the associates value (id). The ge causes the ids to be substituted for every word in the line.

    Perhaps this will clarify things?

    %hash = ( brown=>1, fox=>2, quick=>3, the=>4 );; $line = 'the quick brown fox';; $line =~ s[\b([a-z]+)\b][ $hash{ $1 } ]ge;; print $line;; 4 3 1 2

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      Yes, it did!

      Your solution combined with Kenneth's apparently did the trick. Will try to work around it a little bit tho, see if I can make it quicker.

      Thanks for the help :)

Re^3: using hashes
by hdb (Monsignor) on Sep 26, 2013 at 17:30 UTC

    In order to make things even more complicated I recommend to replace $hash{ $1 } with

    $hash{ $1 } // $1

    which means if $1 is not found in your hash, then replace your word with itself, ie leave it unchanged.

Re^3: using hashes
by aaron_baugher (Curate) on Sep 26, 2013 at 17:16 UTC
        s[\b([a-z]+)\b][ $name_id{ $1 } ]ge;

    The 's' at the beginning says to find a pattern and replace it. The 'g' at the end says to repeat this process as many times as possible. The 'e' at the end says that the replacement part should be evaluated as code, not treated as literal text.

    In the first part, the pattern, the \b matches a "word boundary," the boundary between word characters and non-word characters like your commas. [a-z]+ means a string of 1 or more consecutive lowercase letters. The parentheses around that capture whatever is matched within them and save it in the special variable $1.

    In the replacement part, $1 contains the matched word, so this becomes a simple lookup for that word as a key in the %name_id hash, replacing it with the value corresponding to that key. As mentioned before, because of the 'g', this entire process is repeated for each match found in the line.

    Aaron B.
    Available for small or large Perl jobs; see my home node.