'Assignment of subroutine references in Perl script
I'm learning Perl from Intermediate Perl by Randal Schwartz. Can somebody explain the assignment of the variables $callback and $getter in the following code?
use File::Find;
sub create_find_callbacks_that_sum_the_size {
my $total_size = 0;
return(sub {$total_size += -s if -f}, sub { return $total_size });
}
my %subs;
foreach my $dir (qw(bin lib man)) {
my ($callback, $getter) = create_find_callbacks_that_sum_the_size( );
$subs{$dir}{CALLBACK} = $callback;
$subs{$dir}{GETTER} = $getter;
}
for (keys %subs) {
find($subs{S_}{CALLBACK}, $_);
for (sort keys %subs) {
my $sum = $subs{$_}{GETTER}->( );
print "$_ has $sum bytes\n";
}
Am I right in thinking that $callback gets the value of the first subroutine reference:
sub {$total_size += -s if -f}
And that $getter gets the second subroutine reference:
sub { return $total_size }
Is this a list assignment?
many thanks
Solution 1:[1]
This is a list assignment. The subroutine returns two things. The first thing goes into $callback
and the second thing goes into $getter
:
my ($callback, $getter) = create_find_callbacks_that_sum_the_size( );
So, yes, your answer is right. Each ends up with one of the anonymous subroutines created in the create_find_callbacks_that_sum_the_size
factory.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | brian d foy |