I came across the following code in List::Util for reduce subroutine.
my $caller = caller;
local(*{$caller."::a"}) = \my $a;
local(*{$caller."::b"}) = \my $b;
I could understand that reduce function is called as:
my $sum = reduce { $a + $b } 1 .. 1000;
So, I understood the code is trying to reference $a mentioned in the subroutine. But, I am unable to understand the intent correctly.
For reference, I am adding the complete code for subroutine
sub reduce (&@) {
my $code = shift;
require Scalar::Util;
my $type = Scalar::Util::reftype($code);
unless($type and $type eq 'CODE') {
require Carp;
Carp::croak("Not a subroutine reference");
}
no strict 'refs';
return shift unless @_ > 1;
use vars qw($a $b);
my $caller = caller;
local(*{$caller."::a"}) = \my $a;
local(*{$caller."::b"}) = \my $b;
$a = shift;
foreach (@_) {
$b = $_;
$a = &{$code}();
}
$a;
}
The following aliases package variable
$footo variable$bar.Any change to one changes the other as both names refer to the same scalar.
Of course, you can fully qualify
*foosince it’s a symbol table entry. The following aliases package variable$main::footo$bar.Or, if you don’t know the name at compile time
$bar, of course, can just as easily be a lexical variable as a package variable. And sincemy $bar;actually returns the variable begin declared,can be written as
So,
declares and aliases lexical variables
$aand$bthe similarly named package variables in the caller’s namespace.localsimply causes everything to return to their original state once the sub is exited.