[EMAIL PROTECTED] wrote:
> How do you declare a var global versus local? It seems variables a local
> and not static as in shell. That is, the sub does not see the vars from
> the calling part. So, can someone modify the snipet to make it work?
>
> a.pl
> ------
> #my $x; any diff from the next line?
> $x="abc";
yes.
'my $x="abc";' creates a local variable visible in the whole script.
' $x="abc";' creates a global visible inside and outside the script.
>
> doMe
>
> sub doMe
> { $x="xyz";
you just over writes the value of $x with 'xyz'
> print $x; #will print out xyz
> How can I get the "$x=abc" here w/o passing as an arg?
there is no way to get 'abc' at this point.
> }
you need to undersant how Perl differeniate and handle local and global
variable:
#!/usr/bin/perl -w
use strict;
#--
#-- global $x
#--
our $x = 'abc';
sub doMe{
#--
#-- local $x to doME
#--
my $x = 'xyz';
#--
#-- prints value of $x local to doMe
#--
print $x,"\n";
#--
#-- prints the value of global $x
#--
print $main::x,"\n";
}
doMe;
__END__
prints:
xyz
abc
but if you declare your $x as a local variable like this:
#!/usr/bin/perl -w
use strict;
my $x = 'abc';
sub doMe{
my $x = 'xyz';
print $x,"\n";
}
doMe;
__END__
there is no way for Perl to access the outer local $x from within doMe
because the inner local $x shadow the outer local $x. why would you want to
name 2 local variables the same name anyway?
all this is explained at:
perldoc -q scope
perldoc -q "difference between dynamic and lexical"
david
--
$_=q,015001450154015401570040016701570162015401440041,,*,=*|=*_,split+local$";
map{~$_&1&&{$,<<=1,[EMAIL PROTECTED]||3])=>~}}0..s~.~~g-1;*_=*#,
goto=>print+eval
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]