Perl
  Home arrow Perl arrow Page 2 - Introduction to mod_perl (part 5): Mor...
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
IBM Developerworks
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PERL

Introduction to mod_perl (part 5): More Perl Basics
By: Stas Bekman
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2003-03-12

    Table of Contents:
  • Introduction to mod_perl (part 5): More Perl Basics
  • my() Scoped Variable in Nested Subroutines
  • When You Cannot Get Rid of The Inner Subroutine
  • perldoc's Rarely Known But Very Useful Options
  • References

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    Route your faxes to your email inbox. Private, secure fax numbers available from CallWave. Choose your fax number.

    Introduction to mod_perl (part 5): More Perl Basics - my() Scoped Variable in Nested Subroutines
    (Page 2 of 5 )

    Before we proceed let's make the assumption that we want to developthe code under the strict pragma. We will use lexically scopedvariables (with help of the my() operator) whenever it's possible.

    The Poison

    Let's look at this code:

    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);
    print_power_of_2(6);

    Don't let the weird subroutine names fool you, the print_power_of_2()subroutine should print the square of the number passed to it. Let'srun the code and see whether it works:

    % ./nested.pl
    
    5^2 = 25
    6^2 = 25

    Ouch, something is wrong. May be there is a bug in Perl and it doesn'twork correctly with the number 6? Let's try again using 5 and 7:

    print_power_of_2(5);
    print_power_of_2(7);

    And run it:

    % ./nested.pl
    
    5^2 = 25
    7^2 = 25

    Wow, does it works only for 5? How about using 3 and 5:

    print_power_of_2(3);
    print_power_of_2(5);

    and the result is:

    % ./nested.pl
    
    3^2 = 9
    5^2 = 9

    Now we start to understand--only the first call to theprint_power_of_2() function works correctly. Which makes us think thatour code has some kind of memory for the results of the firstexecution, or it ignores the arguments in subsequent executions.

    The Diagnosis

    Let's follow the guidelines and use the -w flag:

    #!/usr/bin/perl -w

    Under Perl version 5.6.0+ we use the warnings pragma:

    #!/usr/bin/perl
    use warnings;

    Now execute the code:

    % ./nested.pl
    
    Variable "$x" will not stay shared at ./nested.pl line 9.
    5^2 = 25
    6^2 = 25

    We have never seen such a warning message before and we don't quiteunderstand what it means. The diagnostics pragma will certainlyhelp us. Let's prepend this pragma before the strict pragma in ourcode:

    #!/usr/bin/perl -w
    
    use diagnostics;
    use strict;

    And execute it:

    % ./nested.pl
    
    Variable "$x" will not stay shared at ./nested.pl line 10 (#1)
    (W) An inner (nested) named subroutine is referencing a lexical
    variable defined in an outer subroutine.
    When the inner subroutine is called, it will probably see the value of
    the outer subroutine's variable as it was before and during the
    *first* call to the outer subroutine; in this case, after the first
    call to the outer subroutine is complete, the inner and outer
    subroutines will no longer share a common value for the variable.  In
    other words, the variable will no longer be shared.
    Furthermore, if the outer subroutine is anonymous and references a
    lexical variable outside itself, then the outer and inner subroutines
    will never share the given variable.
    This problem can usually be solved by making the inner subroutine
    anonymous, using the sub {} syntax.  When inner anonymous subs that
    reference variables in outer subroutines are called or referenced,
    they are automatically rebound to the current values of such
    variables.
    5^2 = 25
    6^2 = 25

    Well, now everything is clear. We have the inner subroutinepower_of_2() and the outer subroutine print_power_of_2() in ourcode.

    When the inner power_of_2() subroutine is called for the first time,it sees the value of the outer print_power_of_2() subroutine's $xvariable. On subsequent calls the inner subroutine's $x variablewon't be updated, no matter what new values are given to $x in theouter subroutine. There are two copies of the $x variable, nolonger a single one shared by the two routines.

    The Remedy

    The diagnostics pragma suggests that the problem can be solved bymaking the inner subroutine anonymous.

    An anonymous subroutine can act as a closure with respect tolexically scoped variables. Basically this means that if you define asubroutine in a particular lexical context at a particular moment,then it will run in that same context later, even if called fromoutside that context. The upshot of this is that when the subroutineruns, you get the same copies of the lexically scoped variableswhich were visible when the subroutine was defined. So you canpass arguments to a function when you define it, as well as when youinvoke it.

    Let's rewrite the code to use this technique:

    anonymous.pl
    --------------
    #!/usr/bin/perl
    
    use strict;
    sub print_power_of_2 {
    my $x = shift;
    my $func_ref = sub {
    return $x ** 2;
    };
    my $result = &$func_ref();
    print "$x^2 = $result\n";
    }
    print_power_of_2(5);
    print_power_of_2(6);

    Now $func_ref contains a reference to an anonymous function, whichwe later use when we need to get the power of two. (In Perl, afunction is the same thing as a subroutine.) Since it is anonymous,the function will automatically be rebound to the new value of theouter scoped variable $x, and the results will now be as expected.

    Let's verify:

    % ./anonymous.pl
    
    5^2 = 25
    6^2 = 36

    So we can see that the problem is solved.

    More Perl Articles
    More By Stas Bekman


     

       

    PERL ARTICLES

    - Perl: A Continuing Look at Hashes and Multid...
    - Perl: Another Round with Hashes
    - Perl Hashes
    - Perl Lists: A Final Look at List::Util
    - Perl Lists: Utilizing List::Util
    - Perl Lists: The Split() Function
    - SQL and CGI with Perl and DBI
    - Perl Lists: More Functions and Operators
    - SELECT Queries and Perl
    - Perl Lists: More on Manipulation
    - Creating a Database with Perl and DBI
    - Perl: Sailing the List(less) Seas
    - Perl and DBI
    - Perl: Concatenating Text and More
    - Perl Text: Quoting Without Quote Marks

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway