Prabh <> wrote:
> Hello all,
> Is it possible to access a variable with local scope in a subroutine
> from outside of the subroutine?
Yes. Old perl code uses local variables, strict won't like it, and you'll
probably get warnings.
###########################################
$wacky = "Package global";
print "wacky == $wacky\n";
&top_level();
print "wacky == $wacky\n";
sub top_level {
local($wacky); # Variable is now "local" that is, the previous
# data is "pushed" on a stack, during the duration
# of this scope, $wacky will contain the value:
# "Don't do this it's bad"
#
# You'll be able to access $wacky from any sub called
# from here, and on through subs called by those subs, but
# not from the callers scope.
#
# Lots of people will point out that the use of local()
# is generally considered a very bad idea, you can safely
# ignore these people. they are probably the kind of
# people who don't enjoy the taste of licking very cold
# steel either
$wacky = "Don't do this it's bad";
&some_sub();
}
sub some_sub {
print "Value of wacky: $wacky\n";
}
>
> e.g.,
>
> #usr/local/bin/perl
>
> use strict ;
> use warnings ;
>
> sub testScope
> {
> my $var = 10 ;
> }
>
> &testScope ;
> print "$var\n" ;
>
> ==========================================
>
> It doesnt compile with 'use strict', after removing strict, I get
> blank from the print.
>
> Is it possible to retrieve $var in some 'testScope::$var' fashion?
> I realize I could add "return $var;" to the subroutine and access it
> from the out, but was just curious if its possible to access
> variables.
>
> If I dont use "my" or "strict" I can.
> If its a frowned-upon practice, then why does Perl allow it in the
> first place?
>
> Thanks for your time,
> Prab