Re: explain code section please...



On 08/28/2006 03:41 PM, onlineviewer wrote:
Hello All,

Can someone please explain this code section to me. This is from the O'reilly book. learning objects,references. I see the end result, but i am not sure how and in what order it runs. I see that the $callback variable is a reference to the subroutine, 'create_find_callback_that_sums_the_size' then the find method is called with the $callback reference and the bin directory. Then the subroutine executes on each of the contents of the bin directory. Is that right so far ??

Yes

Thanks...

use File::Find;

sub create_find_callback_that_sums_the_size {
my $total_size = 0;

return sub {
if (@_) {
return $total_size;
} else {
$total_size += -s if -f;
}
};

}

my $callback = create_find_callback_that_sums_the_size( );
find($callback, "bin");
my $total_size = $callback->("dummy");
print "total size of bin is $total_size\n";


"$Total_size" is only available within the anonymous subroutine, and the sub, when called without parameters, adds the size of the current file to $total_size and, when called with parameters, outputs $total_size.

The code that returns the anonymous sub might also be written like so:

return sub {
if (@_) {
return $total_size;
} else {
my $current_size = -s $_;
if (-f $_) {
$total_size += $current_size
}
}
};

WARNING: UNTESTED CODE

.



Relevant Pages

  • Re: Memory problem with XML::DOM::Parser???
    ... >> # Die Anfrage ist Teil der neuen EPA ... # Modul für die XML-Funktionen des Clients ... # Subroutine, um die XML-Struktur aus dem XML-Rootfile und den ... sub construct_xml { ...
    (comp.lang.perl.misc)
  • Re: passing database data to a sub
    ... > I'm not sure of the difference, why isn't it a subroutine? ... > sure about this 'shift' thing anyway :-) ... > sub teardown ... > # Setup the template to use for the output. ...
    (perl.beginners)
  • Re: Shared Method Problem With "Global" Storage
    ... Shared Method Problem With "Global" Storage ... declare the Sub as Shared. ... What I don't get is that if I refer to ButtonHasBeenClicked in a subroutine ... code which is unique to mining web site B. ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Proper class setup?
    ... > sub init { ... here: AUTOLOAD and lvalue subroutines. ... if a subroutine named AUTOLOAD exists then it will be called whenever ...
    (perl.beginners)
  • Re: VB app nolonger works with XP SP2
    ... >> Public Sub New ... >> Private components As System.ComponentModel.IContainer ... >> ' This enumeration provides values for the lines sent to the Comm Port ... >> ' This subroutine invokes a thread to perform an asynchronous write. ...
    (microsoft.public.dotnet.languages.vb)