Hi, 

Dhanashri Bhate <[EMAIL PROTECTED]> asked:
[...]
> I can do something like suffixing the filename with timestamp 
> etc, but would like to know if there can be a static variable 
> defined in this function which will be incremented each time 
> a new file is created.

You can model such behaviour in Perl by using closures:

#!/usr/bin/perl

use strict;
use warnings;

sub make_counter {

  # these variables are visible as static variables
  # to the anonymous subroutine below
  my( $start, $step ) = @_;

  # returns a reference to a subroutine that can be
  # called by using the $var->() notation.
  return sub {
    return $start += $step;
  }
}

my $add_one = make_counter(0,1);
my $sub_one = make_counter(5,-1);

for( my $i = 0; $i < 5; $i++ ){
  print $add_one->() . " " . $sub_one->() . "\n";
}
__END__

The above examples demonstrates their usage: You declare a 
generator function that returns a code reference. Your "static"
variables are declared as lexicals in the scope of the generator
function, so that they are visible to an anonymous subroutine.

A call to the generator function will create a fresh set of
lexical variables that will remain accessible to the code of
the code reference that is passed back to you.

For the full scoop on closures and really good examples I'd
recommend the book "Higher-order Perl" by Mark Jason Dominus.

HTH,
Thomas

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


Reply via email to