in reply to return a word next to the word you give

my $word = "color: "; my $lineno = 0; while (<STDIN>) { $lineno++; if (m#$word(\w+)#) { # $1 should now contain the color } }

There's no need to slurp the whole file into memory if you are sure that there will never be a linebreak between the color: and the actual color name.

Also, if you're sure that $word will never change its value, you should postfix the regexp with "o" for efficiency reasons:

if (m#$word(\w+)#o) {

but only if you're 100% sure that the contents of $word will not change!

Hope this helps.

Liz

Replies are listed 'Best First'.
Re: return a word next to the word you give
by Abigail-II (Bishop) on Oct 16, 2003 at 12:32 UTC
    What's /o going to win you here? As running it with -Dr will show, Perl is not going to recompile the regex anyway. And what's with the $lineno++? Did $. break? And since the regex doesn't contain any /'s, why m## and not just //?

    Abigail

      What's /o going to win you here?

      I guess I could ask the same question about the use of quotemeta() in Re: return a word next to the word you give. What's that going to win you there? It's clear there are no characters causing special effects in "color: ", are there? But you're trying to teach a newbie some good idiom, even though it doesn't make any sense performance wise or other wise in this particular case.

      The reason I mentioned /o was that it can be a severe performance penalty if the regexp needs to be compiled again and again if it is not necessary. So I too am trying to teach something to a newbie.

      As running it with -Dr will show, Perl is not going to recompile the regex anyway.

      Has Perl suddenly become psychic? Does Perl now know when and when not to recompile regular expressions with embedded variables? Then why isn't /o deprecated? Just for those few cases where you want to be able to change the variable and still keep the initial regex?

      And what's with the $lineno++? Did $. break?

      Good point. That could have been $..

      And since the regex doesn't contain any /'s, why m## and not just //?

      Well, in my experience, I find myself trying match "/" much more often than I find myself trying to match "#". And I like to be consistent as much as I can, so I prefer doing m## almost all of the time over doing // most of the time.

      Furthermore, I prefer a visual feedback about whether I'm trying to match or replace a string, so even with // I personally prefer to write m//.

      Even though this slipped in without much thought from my end (as it sort of is engrained in my fingers nowadays), it also teaches the newbie that there is more than one way to do it.

      Liz