On Tue, 2005-10-18 at 11:01 +0100, John ORourke wrote:
> 'my' means that it is local to the main program, so your subroutine
> won't see that version of "$counter". Your subroutine will create and
> access a global version of "$counter" which is separate and doesn't get
> re-initialised.
Good guess, but that's not what is happening here. What our flowery
friend has stumbled onto is a closure. When a subroutine references a
"my" variable that was declared outside of that subroutine's scope, the
sub will keep a private copy of that variable. If it wasn't a closure,
it would have just printed "1" over and over. To avoid creating a
closure, you declare the "my" variable inside the subroutine's scope:
sub increment_counter {
my $counter;
$counter++;
print "Counter is equal to $counter !\r\n";
}
But that will never go above 1.
Here's one way to get the intended result without using a global
("our"):
#!/usr/bin/perl -w
use strict;
use warnings;
print "Content-type: text/plain\r\n\r\n";
my $counter = 0;
for (1..5) {
$counter = increment_value($counter);
print "Counter is equal to $counter !\r\n";
}
sub increment_value {
my $value = shift;
$value++;
return $value;
}
- Perrin