Also sprach Picker Leon:
Can you explain this code:
my $input = $_[0];
local $matchkey = $_[1]; # must use local instead of my to be used in
callback
local @output = (); # must use local instead of my to be used in callback
sub callback {
my($tag, %attr) = @_;
if ($tag eq $matchkey) {push(@output, values %attr);};
return;
}
my $p = HTML::LinkExtor->new(\&callback);
$p->parse($input);
Why do I have to use local here? If I just use my @output, should callback
have access @output, because callback is in the same scope with my @output?
I tried using my, but records messed up totally.
And I don't know why use my for $input but local for $matchkey.
In the above code, there is no need for using local().
First thing that can be said about local(), is that only deals with
package variables. Package variables are those that live in a package
(=namespace) and can be qualified:
package Test;
$var = "foobar";
package main;
print $var; # $var is undef here because it is $main::var
versus
package Test;
$var = "foobar";
package main;
print $Test::var; # prints foobar
Compare this with
package Test;
my $var = "foobar";
package main;
print $Test::var; # prints nothing
print $var; # prints foobar
So variables declared with my() are visible only in the enclosing block
or - in case their is no block - throughout the whole file.
local() can now be used to give a package variable temporarily a new
value:
$var = "old value"; # this is a package variable!
{
local $var = "new value";
print $var, "\n";
}
print $var, "\n";
__END__
new value
old value
The previous value is restored when leaving the block in which the
variable was localized.
my() on the other hand doesn't do anything to the value of a variable.
It is used to create _new_ lexical variables. local() on the other hand
does not create variables, it simply gives them a new value. The reason
why local() and my() are often mentioned in the same context is
historical. Perl4 did not have lexical variables, there were only
package ones. So it was impossible to write
sub function {
my ($var1, $var2) = @_;
...
}
instead one had to use global variables inside a function. That's why it
was common to use
sub function {
local ($var1, $var2) = @_;
...
}
in order to make sure that you did not accidently overwrite $var1 and
$var2 elsewhere in your program.
This problem no longer exists with lexical variables because they only
exist in the block in which they were declared:
package main;
{
my $var = "foobar";
}
print $var; # tries to print $main::var
The above will additionally give a fatal error when 'use strict' is in
effect because global variables either have to be declared using our()
or 'use vars'. So our() and 'use vars' are to package variables roughty
what my() is for lexicals. I say 'roughly' because our() the vars pragma
aren't quite the same. our() adds some odd scoping semantics (similar to
those of my()) to package variables. But I suggest you forget about
that. It's more than obscure.
Tassilo