3

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.