--- Jon Cassorla <[EMAIL PROTECTED]> wrote:
> 
> There are many ways to do this.  Here is just one example using a
> closure.
> 
> package Remember;
> 
> # this is a closure
> {
>     my $savedData = 0;    # only accessible within this scope; side
> effect is that
>                           # it stays around as long as the module since
> the following
>                           # method needs it
> 
>     sub rememberData
>     {
>         my $class = shift;
>         $savedData = shift if @_;    # update with new value if given
>         return $savedData;           # return current value
>     }
> }
> 
> 1;
> 
> 
> Here is a test program to validate that the data in $savedData stays
> around.

Actually, you really don't want to try to lexically scope a subroutine like that 
(because you
can't -- well, there is a way, but it involves messing with symbol tables and that's 
usually not a
good idea).

Your code can easily result in mysterious "Variable $foo will not stay shared" errors. 
 Here's a
sample program to show why this is bad practice (even though it looks good):

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

    first( "Ovid" );
    second();
    first( "foo" );

    sub first {
        my $argument = shift;
        second();
    
        sub second {
            print "$argument\n";
        }
    }

That will print "Ovid" three times and warn you that the variable $argument will not 
stay shared.

Cheers,
Curtis "Ovid" Poe

=====
Senior Programmer
Onsite! Technology (http://www.onsitetech.com/)
"Ovid" on http://www.perlmonks.org/

__________________________________________________
Do You Yahoo!?
Make a great connection at Yahoo! Personals.
http://personals.yahoo.com

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to