mod_perl Perl Reference & refs to anonymous subs

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top