in reply to Re: Scope, package, and 'my' variables
in thread Scope, package, and 'my' variables

Thanks for the example. Minor quibble, perhaps it's my 5.8 system, but that second print statement does not fail as undefined. Instead it prints '1'.

#!/usr/bin/perl -w use strict; my $x = 1; BEGIN { $x = 2; } print $x, "\n"; # 1 BEGIN { my $x = 1; } print $x, "\n"; # (sic: ) undefined, failure under strict.pm # Apr 30, 05: Actually, mine doesn't fail and prints '1' my $x = 1; # 'my' generates a 'masks declaration' warning { package foo; $x = 2; } print $x, "\n"; # 2 my $x = 1; # 'my' generates a 'masks declaration' warning { package foo; my $x = 2; } print $x, "\n"; # 1

Replies are listed 'Best First'.
Re^3: Scope, package, and 'my' variables
by revdiablo (Prior) on Apr 30, 2005 at 17:56 UTC

    Each example must be run separately. You're getting the value of $x defined from the previous test. If you run the 2nd one by itself, however:

    $ perl -le ' BEGIN { my $x = 1; } print defined $x ? "defined" : "undefined";' undefined

    And with strict:

    $ perl -Mstrict -le ' BEGIN { my $x = 1; } print $x;' Global symbol "$x" requires explicit package name at -e line 2. Execution of -e aborted due to compilation errors.