mod_perl Perl Reference & refs to anonymous subs

Discussion in 'Perl Misc' started by RA Jones, Aug 18, 2003.

  1. RA Jones

    RA Jones Guest

    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?
    --
    RA Jones
    ra(dot)jones(at)dpw(dot)clara(dot)co(dot)uk
    RA Jones, Aug 18, 2003
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Nagle
    Replies:
    3
    Views:
    290
    John Nagle
    Feb 25, 2007
  2. Replies:
    2
    Views:
    438
    Big and Blue
    Jan 25, 2006
  3. Replies:
    29
    Views:
    194
  4. Replies:
    0
    Views:
    77
  5. Ivan Shmakov
    Replies:
    15
    Views:
    242
    Peter J. Holzer
    Jul 7, 2013
Loading...

Share This Page