As you discovered, lexical vars can be globals too :)
Now try the following snippets:
#!/usr/bin/perl #use strict; use warnings; sub foo { $n++; } $n = 10; print "$n\n"; # 10 foo(); print "$n\n"; # 11
#!/usr/bin/perl use strict; use warnings; sub foo { $n++; } # Compile-time (strict) error! our $n = 10; print "$n\n"; # 10 foo(); print "$n\n"; # 11
#!/usr/bin/perl use strict; use warnings; # "our $n;" disables "use strict 'vars';" for $n for the # remainder of the lexical scope in which it is located. sub foo { our $n; $n++; } our $n = 10; print "$n\n"; # 10 foo(); print "$n\n"; # 11
#!/usr/bin/perl use strict; use warnings; sub foo { my $n; $n++; } # Different $n! my $n = 10; print "$n\n"; # 10 foo(); print "$n\n"; # 10
#!/usr/bin/perl use strict; use warnings; sub foo { $n++; } # Compile-time (strict) error! my $n = 10; print "$n\n"; foo(); print "$n\n";
#!/usr/bin/perl use strict; use warnings; my $n = 10; sub foo { $n++; } print "$n\n"; # 10 foo(); print "$n\n"; # 11
In reply to Re: Using an "outer" lexical in a sub?
by ikegami
in thread Using an "outer" lexical in a sub?
by cornballer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |