G
grocery_stocker
The following code generates even numbers..
[cdalten@localhost oakland]$ more even.pl
#!/usr/bin/perl -w
sub even_number_printer_gen {
# This function returns a reference to an anon. subroutine.
# This anon. subroutine prints even numbers starting from $input.
my($input) = @_;
if ($input % 2) { $input++}; # Next even number, if the given
# number is odd
$rs = sub {
print "$input "; # Using $input,which is a my variable
# declared in an outside scope
$input += 2;
};
return $rs; # Return a reference to the subroutine above
}
my $iterator = even_number_printer_gen(30);
# $iterator now points to a closure.
# Every time you call it, it prints the next successive even number.
for ($i = 0; $i < 10; $i++) {
&$iterator();
}
print "\n";
[cdalten@localhost oakland]$ ./even.pl
30 32 34 36 38 40 42 44 46 48
[cdalten@localhost oakland]$
The thing I'm not seeing why using clousres would be important in this
case. Can someone enlighten me?
[cdalten@localhost oakland]$ more even.pl
#!/usr/bin/perl -w
sub even_number_printer_gen {
# This function returns a reference to an anon. subroutine.
# This anon. subroutine prints even numbers starting from $input.
my($input) = @_;
if ($input % 2) { $input++}; # Next even number, if the given
# number is odd
$rs = sub {
print "$input "; # Using $input,which is a my variable
# declared in an outside scope
$input += 2;
};
return $rs; # Return a reference to the subroutine above
}
my $iterator = even_number_printer_gen(30);
# $iterator now points to a closure.
# Every time you call it, it prints the next successive even number.
for ($i = 0; $i < 10; $i++) {
&$iterator();
}
print "\n";
[cdalten@localhost oakland]$ ./even.pl
30 32 34 36 38 40 42 44 46 48
[cdalten@localhost oakland]$
The thing I'm not seeing why using clousres would be important in this
case. Can someone enlighten me?