Not quite a question, but as I just was sort of bitten of this...

Take a look on the code and think about what it would output; then try it out, just to have your confirmation:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; _test(); exit; ######## subroutines { my @values = qw( 1 2 3 ); sub _test { print "Values:\n", Dumper( \@values ); } }
Have fun - and congratulations if you got it right at first look! ;)

Krambambuli

Replies are listed 'Best First'.
Re: Check your wits
by JavaFan (Canon) on Aug 08, 2008 at 14:48 UTC
    Uhm, what's so exiting about it? You're dumping @values before it has had a chance to be initialized (the variable exists, it was defined at compile time, but the assignment hasn't happened, as at run time, it hasn't gotten past the assignment yet - and in fact, it never will).

      "Obviously" the script is flawed, but the real question is did you see it before you ran the script or afterwards:-)

      For the record: I did afterwards:-/ Gestalt Principles of Perception?

        Before. I took the approach of identifying difference with what I would do. I immediately saw two things: code before functions, and use of exit. I looked if there was more code below exit, and voila!

        The fix is to add one word:

        #!/usr/bin/perl use strict; use warnings; use Data::Dumper; _test(); exit; ######## subroutines BEGIN { <----- my @values = qw( 1 2 3 ); sub _test { print "Values:\n", Dumper( \@values ); } }
        I saw it before I ran the script. But obviously, from how the question was framed, I knew in advance there was something fishy. And the shortness of the code didn't leave many options of what would be wrong.

        Would I have seen it if the program was larger, and it wasn't flagged as "there's something going on here"? Probably not.

        I didn't see it because I was expecting some closure pitfall and was searching for that to the exclusion of everything else.
Re: Check your wits (practices)
by tye (Sage) on Aug 09, 2008 at 06:04 UTC

    That's a classic "gotcha" in my book. That's one reason why I almost always write such code as:

    { my @values; BEGIN { @values = ( 1 .. 3 ); } sub _test { # ... } }

    or, especially if the code is going into the main script for a mod_perl Apache::Registry page:

    BEGIN { my @values = ( 1 .. 3 ); sub _test { # ... } }

    Actually, that makes me wonder why I've been using the first form lately. I should switch back to the second form. Thanks for reminding me.

    Oh, and to be extra clear, yes, it is easy to get caught by this problem (which is why I have a "practice" for preventing it).

    - tye        

Re: Check your wits
by dreadpiratepeter (Priest) on Aug 09, 2008 at 03:36 UTC
    I saw it immediately, but I got bit by that very bug today, so I was extra-sensitive to it.


    -pete
    "Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."