R
RA Jones
The source for this question is 'Perl Reference' at
<http://perl.apache.org/docs/general/perl_reference/perl_reference.html>.
Under the section 'my() Scoped Variable in Nested Subroutines - The
Poison', the following is quoted:
nested.pl
#!/usr/bin/perl
use strict;
sub print_power_of_2 {
my $x = shift;
sub power_of_2 {
return $x ** 2;
}
my $result = power_of_2();
print "$x^2 = $result\n";
}
print_power_of_2(5); # produces 25
print_power_of_2(6); # also produces 25!
The solution is to use a reference to an anonymous subroutine in place
of power_of_2, which deals with the problem of variables not staying
shared.
But isn't this 'problem' caused in the first place by print_power_of_2
not handing on to power_of_2 the value originally handed to it, and
letting power_of_2 take $x into its own local variable?
For example the following seems much simpler, and doesn't need to use a
reference to an anonymous subroutine:
sub print_power_of_2 {
my $x = shift;
sub power_of_2 {
my $x =shift;
return $x ** 2;
}
my $result = power_of_2($x);
print "$x^2 = $result\n";
}
print_power_of_2(5); # produces 25
print_power_of_2(6); # now correctly produces 36
Is there a penalty incurred by doing it this apparently simpler way?
<http://perl.apache.org/docs/general/perl_reference/perl_reference.html>.
Under the section 'my() Scoped Variable in Nested Subroutines - The
Poison', the following is quoted:
nested.pl
#!/usr/bin/perl
use strict;
sub print_power_of_2 {
my $x = shift;
sub power_of_2 {
return $x ** 2;
}
my $result = power_of_2();
print "$x^2 = $result\n";
}
print_power_of_2(5); # produces 25
print_power_of_2(6); # also produces 25!
The solution is to use a reference to an anonymous subroutine in place
of power_of_2, which deals with the problem of variables not staying
shared.
But isn't this 'problem' caused in the first place by print_power_of_2
not handing on to power_of_2 the value originally handed to it, and
letting power_of_2 take $x into its own local variable?
For example the following seems much simpler, and doesn't need to use a
reference to an anonymous subroutine:
sub print_power_of_2 {
my $x = shift;
sub power_of_2 {
my $x =shift;
return $x ** 2;
}
my $result = power_of_2($x);
print "$x^2 = $result\n";
}
print_power_of_2(5); # produces 25
print_power_of_2(6); # now correctly produces 36
Is there a penalty incurred by doing it this apparently simpler way?