On Mon, Apr 21, 2008 at 10:40 AM, J. Peng <[EMAIL PROTECTED]> wrote:
> I'm not sure, but why this can work?
>
>  use strict;
>  use warnings;
>  use Data::Dumper;
>
>  my $y=0;
>  my @x =(1,2,3) if $y;
>  print Dumper [EMAIL PROTECTED];
>
>
>  Since $y is false, it seems @x shouldn't be declared.
>  But why the last print can work?
snip

Because of a quirk in how the current and past versions of perl parsed
and handled the statement.  It is a mis-feature according to Larry.
Some people used to use it to create state variables.  The correct way
to create a state variable prior to 5.10 is with a closure:

{
    my @x = (1, 2, 3);
    sub function_that_uses_x {
        ...
    }
}

In Perl 5.10 we got the state* function that works like the my
function but does not reinitialize each time through:

sub function_that_uses_x {
    state @x = (1, 2, 3);
    ...
}

Of course, the old way is still handy if you need to share a state
value between functions:

{
    my $shared = 0;
    sub f1 {
        ...
    }
    sub f2 {
        ...
    }
}

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to