Gossamer Forum
Home : General : Perl Programming :

local vs my

Quote Reply
local vs my
In a script I have the following line:

Code:
sub main {
# --------------------------------------------------------
local (%in) = &parse_form;
Now, I would like to have local (%in) = &parse_form_adv if my var $browser is true. I saw the following code somehere, but it uses my. Can I just change my into local?

Code:


my %FORM;

if($browser eq "true") {
%FORM = &parse_form;
}
else {
%FORM = &parse_form_adv;
}
Quote Reply
Re: local vs my In reply to
my is used when you want to assign the given variable, array or hash to the sub-routine it is placed in and that sub-rotuine only.

local is used when you want to assign the given variable, array or hash to the sub-routine is is placed in and all sub-routines being called from within that sub-routine.

Example.

sub example_sub1 {

my $varialbe;

# insert sexy coding

}

sub example_sub2 {

local $variable;

&another_sub($variable);

# insert sexy coding

}


Sorry for the bad example, but I'm trying my best to explain here :-)

Rgds,
Wiliam Stephens

Quote Reply
Re: local vs my In reply to
Sort of. If you try your example 2, but use my instead of local, it will still work if you're not under strict. =)

The my() and local() constructs have far more technical differences, that are reallllly long and boring. In short, local was more of a perl 4 construct, and my is now the more appropriate.

In short, you should ALWAYS use my, except for when you NEED to use local. If you don't know when you NEED to use local, then you don't need to. =)

--mark

Installation support is provided via ICQ at UIN# 53788453. I will only respond on that number.
Quote Reply
Re: local vs my In reply to
'my' scopes a variable lexically within the block, eval, file or sub that it was called in as an independent variable to the perl interpereter. (i.e. a completely separate data stack from the global version)

'local' scopes a global variable locally within its block, eval, file or sub. the original value of the variable(s) is stored in a temporary hidden stack until the block, eval, sub or file is finished executing and then reassigned to the variable.

so the moral of this story is, if you don't know the diff, just use my. even if you do know, you probably want to use it anyway:)

-- Gordon


s/(\d{2})/chr($1)/ge + print if $_ = '8284703280698276687967';