in reply to A curious case of of my()

$href is empty, since it is not passed into foo. hence @array ends up being a package variable and not a lexical variable.
your code
sub foo{ my $var = shift; my $href = shift; my @array = $href->{pass_in} if defined $href and exists $href +->{pass_in}; push @array, $var; print "contents : @array\n"; } foo(1); foo(2);
This gives
contents : 1
contents : 1 2

However, commenting out the unused href code and declaring array as a lexical like:

sub foo{ my $var = shift; my @array; #my $href = shift; #my @array = $href->{pass_in} if defined $href and exists $hre +f->{pass_in}; push @array, $var; print "contents : @array\n"; } foo(1); foo(2);
gives

contents : 1
contents : 2

I hope for nothing. I fear nothing. I am free.

Replies are listed 'Best First'.
Re^2: A curious case of of my()
by shmem (Chancellor) on May 05, 2011 at 10:34 UTC
    $href is empty, since it is not passed into foo. hence @array ends up being a package variable and not a lexical variable.

    As others have pointed out, that's wrong. my creates lexicals at compile time. It doesn't have a our fallback. The 'if' modifier with a false condition inhibits the opcode which clears the lexical at runtime.

    our @array; # package vaiable @array = qw( foo bar ); sub foo{ my $var = shift; my $href = shift; my @array = $href->{pass_in} if defined $href and exists $href +->{pass_in}; push @array, $var; print "contents : @array\n"; } print "outer scope - contents : @array\n"; foo(1); foo(2); print "outer scope - contents : @array\n"; __END__ outer scope - contents : foo bar contents : 1 contents : 1 2 outer scope - contents : foo bar

    As you can see, the variable @array inside the sub is a lexical.