Perl
  Home arrow Perl arrow Page 2 - Introduction to mod_perl (part 5): More Perl Basics
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 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? 
Google.com  
PERL

Introduction to mod_perl (part 5): More Perl Basics
By: Stas Bekman
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    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 develop the code under the strict pragma. We will use lexically scoped variables (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's run 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't work 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 the print_power_of_2() function works correctly. Which makes us think that our code has some kind of memory for the results of the first execution, 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 quite understand what it means. The diagnostics pragma will certainly help us. Let's prepend this pragma before the strict pragma in our code:

      #!/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 subroutine power_of_2() and the outer subroutine print_power_of_2() in our code.

    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 $x variable. On subsequent calls the inner subroutine's $x variable won't be updated, no matter what new values are given to $x in the outer subroutine. There are two copies of the $x variable, no longer a single one shared by the two routines.

    The Remedy

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

    An anonymous subroutine can act as a closure with respect to lexically scoped variables. Basically this means that if you define a subroutine in a particular lexical context at a particular moment, then it will run in that same context later, even if called from outside that context. The upshot of this is that when the subroutine runs, you get the same copies of the lexically scoped variables which were visible when the subroutine was defined. So you can pass arguments to a function when you define it, as well as when you invoke 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, which we later use when we need to get the power of two. (In Perl, a function is the same thing as a subroutine.) Since it is anonymous, the function will automatically be rebound to the new value of the outer 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

    - More Perl Bits
    - Perl, Bit by Bit
    - Basic Charting with Perl
    - Using Getopt::Long: More Command Line Option...
    - Command Line Options in Perl: Using Getopt::...
    - Web Access with LWP
    - More Templating Tools for Perl
    - Site Layout with Perl Templating Tools
    - Build a Perl RSS Aggregator with Templating ...
    - Looping, Security, and Templating Tools
    - Perl: Bon Voyage Lists and Hashes
    - Templating Tools
    - Perl: Number Crunching
    - Perl Debuggers in Detail
    - Debugging Perl





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek