From:                   Richard Lee <[EMAIL PROTECTED]>
> trying to understand closure and callback(bit over my head but)
> 
> while I think i grasp most of the ideas from below program.. I don't 
> think I understand why ( ) is needed in
> 
> my $sum = $subs{$_}{GETTER}->( );

Because $subs{$_}{GETTER} is a subroutine reference and you need to 
"dereference" it. And just like you can use either
${$arrayref}[1] or $arrayref->[1] to dereference a reference to an 
array you can use either &{$subref}(1) or $subref->(1) to dereference 
a reference to a subroutine (that is to call the referenced 
subroutine). In your particular case you just do not need to pass any 
parameters so it would be $subs{$_}{GETTER}->( ) or 
&{$subs{$_}{GETTER}}.

HTH, Jenda
 
P.S.: Of course the example is a little convoluted. If you did not 
want to use a global variable you could do something like this:

#!/usr/bin/perl
use warnings;
use strict;

use File::Find;

sub sum_size_into {
     my $total_size = shift;
     die "sum_size_into() parameter must be a scalar ref!" unless 
ref($total_size) eq 'SCALAR';
     return sub { $$total_size += -s if -f };
}

for my $dir ( qw(bin lib man) ) {
    my $sum = 0;
    find( sum_size_into(\$sum) , $dir);
    print "$dir has $sum bytes\n";
}

That is instead of generating a callback and a getter, you specify 
where should the callback store the result.

Or, since the action is fairly simple and there is little need for a 
callback generator:

use warnings;
use strict;

use File::Find;

for my $dir ( qw(bin lib man) ) {
    my $sum = 0;
    find( sub { $sum += -s if -f }, $dir);
    print "$dir has $sum bytes\n";
}

===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
        -- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to