Click to See Complete Forum and Search --> : my & our in PERL


BRT
02-10-2001, 11:37 PM
I'm new to Perl and am having no real problems despite the explanation of the my and our functions (or lack thereof) that my book has. Could someone explain these functions to me.

Thanx

YaRness
02-11-2001, 05:39 PM
"my" is used in the traditional sense to create a local variable.


sub foo
{
my $yar = "foo";
print "$yar\n";
}
my $yar = "bar";
print "$yar\n";
foo();
print "$yar\n";


the "$yar" variable above is visible only inside subroutine "foo". any references to "$yar" inside "foo()" will have the value 'foo'.

"our" is a little different, it allows a variable to be limited in scope, but cross package boundaries. i haven't played with it, so i don't want to try and explain it. you can look at "perldoc -f our" if you have perldoc on your system, or look in the perlfunc man page.

lazy_cod3R
02-12-2001, 08:26 AM
whats the difference between my and local ?
doest local define a local variable as well ?

YaRness
02-12-2001, 09:51 AM
local does not quite do what you might think intuitively. if you change the "my" in sub foo to "local", what it does is save the original value of the variable, and then let you play with it in that subroutine however you wish, and then it restores it to it's original value afterwards. i guess the difference is it's the same variable (i.e. space in memory), whereas with "my" you get a completely different space in memory (that is, only the name of the variable is overrided, the original space in memory for the original variable is never touched). 'local' is mostly useful now for playing with the default variables (@_ and $_), 99.9% of the time you want to use "my".

see also "perldoc -f local", and the perlsub and perlfunc man pages.

from the perlsub man page:
WARNING: In general, you should be using 'my' instead of 'local', because it's faster and safer. Exceptions to this include the global punctuation variables, filehandles and formats, and direct manipulation of the Perl symbol table itself. Format variables often use local though, as do other variables whose current value must be visible to called
subroutines.
...
A local modifies its listed variables to be ``local'' to the enclosing block, 'eval', or 'do FILE'--and to any subroutine called from within that block. A local just gives temporary values to global (meaning package) variables. It does not create a local variable. This is known as dynamic scoping. Lexical scoping is done with 'my', which works more like C's auto declarations.


[ 12 February 2001: Message edited by: YaRness ]