in reply to scope of an autovivified variable?

From perlsyn:

NOTE: The behaviour of a my statement modified with a statement modifier conditional or loop construct (e.g. my $x if ... ) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.

I think that's clear enough. And perlsyn is far from obscure documentation.

Update:

Perl doesn't natively complain to you if you use such a construct. However, there's a tool that I have in my arsenal which is so simple to use that I've managed to make it a habit as I work on scripts. Start with Perl::Critic. Next, create a Perl script based on the synopsis of Perl::Critic's documentation, as follows:

use Perl::Critic; my $file = shift; my $critic = Perl::Critic->new(); my @violations = $critic->critique( $file ); print @violations;

Now, name that script 'criticize', and put it in your favorite toolbox bin directory. Finally, as you're composing scripts, periodically pass it through the complaint department like this:

criticize mytest.pl

And the output for the specific 'violation' we're discussing:

Variable declared in conditional statement at line 9, column 1. Declar +e variables outside of the condition.

Dave

Replies are listed 'Best First'.
Re^2: scope of an autovivified variable?
by rmcgowan (Sexton) on May 11, 2011 at 20:06 UTC

    Thank you.

    I don't think I said anything about obscure, I just said I couldn't find anything about it.

    That's because I was focused on 'autovivification' and was searching for references to that word, not for use of 'my' in a conditional construct.

      I wasn't suggesting that it was easy to search for. In fact, the entire issue ought to be more searchable; it's a question that gets asked here often. I don't know of a perlfaq that covers it, but it's one of those things that comes up often enough it should be part of the FAQ.

      I probably should have been more specific. What I meant was that perlsyn is one of the top ten 'must read' documents for someone using Perl. perlintro, perlsyn, perlop, perlvar, perlsub, perldata, perlre... ok, that's top seven. ;)

      "Why is my( $variable ) = 'something' if $condition; almost certainly an error?" seems like a very good candidate entry for perlfaq7, though. ;)


      Dave