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


in reply to var comparison

Your question is "simple" but also complex.

My question to your question is: why?
Shorter code doesn't mean more efficient code.
Your first version is very clear and it will run quickly.
String compare is a very performant operation.
I guess that there is something about this question that you haven't told us about?

The first version will normally execute faster and it is more clear. What is the problem?

Replies are listed 'Best First'.
Re^2: var comparison
by nemesisgus (Acolyte) on Sep 07, 2012 at 16:37 UTC

    There were no hidden intentions. My question was simply the product of my poor knowledge of Perl :^)

    Although it's true that shorter doesn't always mean more efficient, it's also true that when you start with a language you tend to use long and complicated expressions to accomplish tasks that, once you have a little (or no so little) more knowledge, you realize that could have been done in a much shorter (and usually clearer) way.

    I was just wondering if this was the case, so the expression:

    $var eq 'foo' || $var eq 'bar'

    could be translated to something like:

    $var eq (foo|bar) (which, of course, does not work)

    or similar, the same way the defined-or operator helps to turn $x = $x // 5 into $x //= 5, for instance.

    (I understand that the implications of doing $var eq (foo|bar) would probably be more complex).

    Consider also that the case I proposed had only two options to compare, so the first version is OK, but with more options a shorter manner would be appreciated. Since that seems not possible, a function would be the best solution as suggested by MidLifeXis.

      I think that $var eq 'foo' || $var eq 'bar' will work very well. If $var is say 'xyz', the string compare will be abandoned at the first letter. "Oh, its not an 'f', lets see if the first letter is an 'b' ... The regex engine is amazing but an expression like this will just call a low level 'C' function that is very efficient.

      My point is that "shorter" source code is not necessary "better" in terms of efficiency or readability.

      If your list of possible values gets long, you could store them as keys of a hash and then check for existence or definedness in the hash.

        Yes, that's one of the solutions MidLifeXis proposed and I think it's also considered a Perl "best practice".