Re: Strange interaction of "my"-variables with initialization
- From: krahnj@xxxxxxxxx (John W. Krahn)
- Date: Sun, 13 Jan 2008 15:10:21 -0800
Chas. Owens wrote:
On Jan 13, 2008 1:20 PM, John W. Krahn <krahnj@xxxxxxxxx> wrote:
snip
Statements don't define scope, braces and files define scope.snipsnipso why should you be able to use it because it has been changed to thisYou can use it because it is in the same scope.
my $t = $x if $x;
print "$t\n";
And that is why I consider it to be a bug. There is no reason for
conditional modifiers to not have their own scope. For instance, the
conditional form of for still localizes $_, even though there is no
scope for it to be localized in:
This is just the way that Perl works:
perldoc perlsyn
[ SNIP ]
Foreach Loops
The "foreach" loop iterates over a normal list value and sets the
variable VAR to be each element of the list in turn. If the
variable is preceded with the keyword "my", then it is lexically
scoped, and is therefore visible only within the loop. Otherwise,
the variable is implicitly local to the loop and regains its former
value upon exiting the loop. If the variable was previously
declared with "my", it uses that variable instead of the global one,
but it’s still localized to the loop. This implicit localisation
occurs only in a "foreach" loop.
The same localization of $_ also occurs with map and grep.
$ perl -le'
$_ = "foo";
map $_ += 1, @x = 1 .. 3;
print "$_ @x";
'
foo 2 3 4
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
.
- References:
- Strange interaction of "my"-variables with initialization
- From: Peter Daum
- Re: Strange interaction of "my"-variables with initialization
- From: Chas. Owens
- Re: Strange interaction of "my"-variables with initialization
- From: John W. Krahn
- Re: Strange interaction of "my"-variables with initialization
- From: Chas. Owens
- Strange interaction of "my"-variables with initialization
- Prev by Date: Re: Controlling external I/O with Perl
- Next by Date: die() (was: which is better ...)
- Previous by thread: Re: Strange interaction of "my"-variables with initialization
- Next by thread: Re: Strange interaction of "my"-variables with initialization
- Index(es):
Relevant Pages
|