Oops.  My bad.  I wonder how much extra work that one's cost me...

-----Original Message-----
From: Jenda Krynicky [mailto:[EMAIL PROTECTED]]
Sent: Monday, April 08, 2002 8:49 AM
To: Timothy Johnson
Cc: [EMAIL PROTECTED]
Subject: RE: Scope of variables. Lost in subs


From: "Timothy Johnson" <[EMAIL PROTECTED]>
> Another thing to remember is that declaring a variable with my() at
> the top of your script does NOT make the variable global.

Right.

>  It loses
> scope in subroutines.  

Wrong.

If you declare a variable with my() its scope will be from the 
declaration to the end of the enclosing block. Which for variables 
declared outside any {} block or eval"" means ... to the end of the 
file.

Including any subroutines.

Unless of course there is another variable with the same name 
declared in a block. In that case this "global" variable is masked till 
the end of that block.

> The easiest way to get around this is to pass
> variables to your subs by reference.

Variables are actually passed kind-of by reference. Try this:

        $x = 20;
        sub foo {
                print "foo called with param $_[0]\n";
                $_[0] = 99;
        }
        print "\$x = $x\n";
        foo($x);
        print "\$x = $x\n";

Or

        @a = (1,2,3);
        sub foo {
                print "foo called with param $_[0], $_[1], $_[2]\n";
                $_[0] = 99;
                $_[1] = 99;
                $_[2] = 99;
        }
        print "\@a = @a\n";
        foo(@a);
        print "\@a = @a\n";

It's when you do
        my $param = shift();
or
        my ($one,$two) = @_;
when you are making copies.

Jenda

=========== [EMAIL PROTECTED] == http://Jenda.Krynicky.cz ==========
There is a reason for living. There must be. I've seen it somewhere.
It's just that in the mess on my table ... and in my brain
I can't find it.
                                        --- me


--------------------------------------------------------------------------------
This email may contain confidential and privileged 
material for the sole use of the intended recipient. 
If you are not the intended recipient, please contact 
the sender and delete all copies.

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

Reply via email to