Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Scope in use

by Anonymous Monk
on Sep 04, 2017 at 13:51 UTC ( #1198664=note: print w/replies, xml ) Need Help??

in reply to Scope in use

I don't see how the current behavior could possibly be called "good." The scope of a my variable doesn't start until the end of the statement it appears in...

>perl -wle 'print($x, (my $x = 42), $x);print "now $x"' Use of uninitialized value $x in print at -e line 1. Use of uninitialized value $x in print at -e line 1. 42 now 42

... so AFAICT there's no way to refer to a lexical created in a use statement at all.

But why would you write
use lib my $lib = '.';
in the first place? Probably because this doesn't work:
my $lib = '.';
use lib $lib;
This seems to be a common problem that people run into. Should we tell them to write this instead?
my $lib = '.';
unshift @INC, $lib;
Or maybe this?
BEGIN { our $lib = '.' }
use lib our $lib;
IDK, but IMO that's the real issue.

Replies are listed 'Best First'.
Re^2: Scope in use
by RonW (Vicar) on Sep 06, 2017 at 20:13 UTC

    The following also works, though is equally surprising that it is needed.

    my $lib; use lib $lib = '.';

    This works because variables declared at one scope are accessible from scopes inside the declaring scope.

    Unfortunately, there isn't a good way to change this. It can, and probably should be, documented in the page for use and, maybe, also in the page for the lib pragma.

    (Maybe a warning could be added when parsing use to remind people that my inside use has no effect and suggest alternate syntax.)

      I think it's enough to document it together with scoping in general - Wherever that happens - as edge case of the "till the end of the surrounding block" rule.

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1198664]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2018-08-21 12:01 GMT
Find Nodes?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:

    Results (198 votes). Check out past polls.