On 12/15/06, John W. Krahn <[EMAIL PROTECTED]> wrote:
Jorge Almeida wrote:
> I thought I already knew a few things about Perl, but I just found out I
> don't:
> #!/usr/bin/perl -w
> use strict;
> use diagnostics;
> my $a="27";
> doit();
> sub doit{
> print "$a\n";
> }
>
> The output of this program is:
> 27
>
> Just what I would expect if line 4 had "our" instead of "my".
> What am I missing?
my() and our() have the same scoping so they will behave the same. my()
variables are scoped from the point they are declared up to the end of the
current file/block. Since your variable is not inside a block it is visible
throughout the rest of the file. By the way, you shouldn't use $a or $b as
they are "special" variables.
More differences will show up if you use packages. The my() variables
will have the scoping from the point they are declared to the end of
the package. The our() variables have the same scoping, but may be
reached by other packages.
$ perl -e 'use strict; use warnings;
package foo;
our $VAR = 0;
sub p_var { print "$VAR\n" }
package main;
$foo::VAR = 1; # this is the same variable above
foo::p_var;
'
1
$ perl -e 'use strict; use warnings;
package foo;
my $VAR = 0;
sub p_var { print "$VAR\n" }
package main;
$foo::VAR = 1; # this is NOT the same variable above
foo::p_var;
'
Name "foo::VAR" used only once: possible typo at -e line 6.
0
There is more to tell the truth. For instance, the lexical variables
created by my() can't be localized. You may read about it at:
perldoc -f my
perldoc -f our
perldoc perlsub (section "Private variables via my()")
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>