in reply to Pseudo-switch question

This looks like good, idiomatic Perl code, fletcher -- nothing to worry about.

The one "side effect" is that it temporarily exposes the test value in the global $_, such that it could be accessed from within a subroutine called from within one of your # do something blocks, although this isn't likely to cause problems in properly written code.

Replies are listed 'Best First'.
Re: Re: Pseudo-switch question
by pemungkah (Priest) on Jul 22, 2003 at 16:12 UTC
    And of course, if you use this in a sub you've clobbered $_. Add a
    local $_;
    previous to your preferred switch method and your callers will thank you.
      Doesn't "for" always automatically localize "$_" like in this example?
      my @list = qw(I Like tacos); for (@list) { print "A:".$_."\n"; for ("Hello") { print "B:".$_."\n"; } print "C:".$_."\n"; }
      It is good that you considered that type of problem, but in this case, it is harmless.

      My rule of thumb is that when using a for/foreach loop, you do not need to localize $_, but if you are using a while(<>) loop, you must localize it.

      This is because the for/foreach loop is already doing the local step for you, but it is the only time that this happens.

        You are indeed correct. I've just gotten into the habit of localizing globals when I'm about to alter them, and I want to be sure I didn't sabotage someone else up the line.

        I tend to assume that someone else reading the code might not think about $_ being global, alter the code so that $_ would get clobbered, and then be confused. If I've localized $_, and also commented why I've done it, it makes it easier to maintain. And I'm all about maintaining.

        I suppose the Right Thing would be to not localize and comment that the for loop does it for me. :)