While your short description of local may well be correct, I think a correct understanding of it depends very much on understanding what a value is, and that this can only be correctly understood with an understanding of perl's internal data structures. To someone unfamiliar with the internals, I think it is easily misunderstood.
To clarify, notice the effect on $x, $y and $$z in the following example:
$x = 10;
*y = *x;
$z = \$x;
{
print "\$x = $x, \$y = $y, \$\$z = $$z \n";
local $x;
print "\$x = $x, \$y = $y, \$\$z = $$z \n";
$x = 20;
print "\$x = $x, \$y = $y, \$\$z = $$z \n";
}
Which produces:
$x = 10, $y = 10, $$z = 10
$x = , $y = , $$z = 10
$x = 20, $y = 20, $$z = 10
It is easy to interpret your description to mean that $$z would change as local $x changed. Yet it doesn't.
The re-initialization of $x and $y may also be a bit of a surprise, even to someone who read Temporary Values via local(). This is subtly hinted at by A "local" just gives temporary values to global (meaning package) variables., but I find that It does not create a local variable. is particularly prone to mislead. In this case, whether the statement is correctly understood or not depends on the understanding of variable which, again, can only be correctly understood with an understanding of perl's internal data structures.
update: Rereading Temporary Values via local() is see: As for simple variables, this creates new, dynamically scoped values.. So, it doesn't create new variables but it does create new values. This may make the initialization of the local'ized variables less surprising.
Compare this with explicitly saving and restoring the variable, as your description of local suggests:
$x = 10;
*y = *x;
$z = \$x;
{
print "\$x = $x, \$y = $y, \$\$z = $$z \n";
$savex = $x;
print "\$x = $x, \$y = $y, \$\$z = $$z \n";
$x = 20;
print "\$x = $x, \$y = $y, \$\$z = $$z \n";
$x = $savex;
}
Which produces:
$x = 10, $y = 10, $$z = 10
$x = 10, $y = 10, $$z = 10
$x = 20, $y = 20, $$z = 20
This also occurs with the implicit localization of the foreach loop.
$x = 10;
*y = *x;
$z = \$x;
foreach $x (1..3) {
print "\$x = $x, \$y = $y, \$\$z = $$z \n";
}
produces:
$x = 1, $y = 1, $$z = 10
$x = 2, $y = 2, $$z = 10
$x = 3, $y = 3, $$z = 10
This is not necessarily inconsistent with your description, but it may be surprising to some, so I thought worth pointing it out to others. There is more on this elsewhere, including Difference b/w my and local var?
|