in reply to Perl Variables storage location and scope question.
Now, what I don't get is, if within the function, I declare the $val as my $val (lexical scope), no warning message is shown. Nothing like "masking earlier declaration of $val". It just treats it as if it were a different variable.
see Coping with Scoping for a much better explanation than I could ever give. But I'll try, so that the explanations stay specific to what you're asking about.
When you declare the $val as lexical scope, its lexical scope is limited to the tightest enclosing block (in this instance, the file, or the first or second functions). A deeper scope (for example, a function inside the file-scope, or a block inside the function-scope) will inherit the value from its containing scope, unless it has a lexically-scoped variable of the same name. In the first program, your only scope for $var was the file-level scope (0x1c307c8), so when you edit $var inside the functions, it's editing the file-scope variable, even from the functions. But in the second program, the first subroutine has its own lexical $val at 0xb2d888, so anything you do to that is limited to that scope; similarly, second's 0xb2e290 is limited to its own scope.
This example shows some of the scopes, and when a "masks earlier declaration" will arise:
use strict; use warnings; my $val = 1; print "my own scope: $val\n"; { my $val = 2; print "my own scope: $val\n"; { print "inherit: $val\n"; # this is another scope, but doesn +'t have an override of the val=2 $val = 2.5; print "edit: $val\n"; # now it's a different value } print "keep the value edited: $val\n"; # which it keeps here { my $val = 3; # this is another scope with it's +own lexical $val, so the previous $val's are invisible to me print "my own scope: $val\n"; } my $val = -2; # warning: masks earlier declaration in same scope print "when scopes collide: $val\n"; } print "back in original file scope: $val\n";
|
|---|