If you 'use strict;' like me, then you need to declare global variables and most
people make use of 'my' for this. Alternatively you can 'use vars':
use strict;
use vars qw($scalar @list %hash);
> I am under the impression that my is for the following:
>
> my $var = 'Whatever';
>
> sub Hey
> {
> print $var;
> }
>
> Shouldn't print anything...
Wrong (the reason your code doesn't print is because you don't call &Hey):
calling &Hey would print 'Whatever'!
But you can declare a new $var within a block using my - try the following:
use strict;
my $var = "Whatever";
print "$var\n";
&Hey;
print "$var\n";
sub Hey {
print "In: $var\n";
my $var = "Something";
print "In: $var\n";
}
If you run this with -w you will get a '"my" variable $var masks earlier
declaration in same scope...'. We get this because we have already used $var in
the scope (Hey sub) before using my. To avoid the error we must declare the
variable as local (lexically) to the enclosing block, via 'my', before using it
but then we cannot access the global $var. If we need access to the global $var
we have to use the keyword 'local' to create a temporary version of $var on the
stack:
use strict;
use vars qw($var);
$var = "Whatever";
print "$var\n";
&Hey;
print "$var\n";
sub Hey {
print "In: $var\n";
local $var = "Something";
print "In: $var\n";
}
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'. See perlsub for more details.
--
Simon Oliver
---
You are currently subscribed to perl-win32-users as: [archive@jab.org]
To unsubscribe, forward this message to
[EMAIL PROTECTED]
For non-automated Mailing List support, send email to
[EMAIL PROTECTED]