develooper Front page | perl.perl6.users | Postings from July 2021

Re: use lib and locations in a variable

Thread Previous | Thread Next
Joseph Brenner
July 13, 2021 17:07
Re: use lib and locations in a variable
Message ID:
Elizabeth Mattijsen <> wrote:

>>  Joseph Brenner <> wrote:

>> I find that while this works:
>>    use lib $*PROGRAM.parent.add('../lib');
>> This doesn't work:
>>    my $lib_loc = $*PROGRAM.parent.add('../lib');
>>    use lib "$lib_loc";
>> I get a compile time error
>>    Use of uninitialized value $lib_loc of type Any in string context.

> This can be easily fixed in Raku: the BEGIN statement can also be used as a
> prefix:
>     BEGIN my $lib_loc = $*PROGRAM.parent.add('../lib');
>     use lib "$lib_loc";

Yes that's a good fix.  Bruce Gray points out "constant" works also:

     constant $lib_loc = $*PROGRAM.parent.add('../lib');

> One note: I'm a bit surprised of the mixture of OS dependent (../) and OS
> independent (.parent) directory walking.  I guess you meant:
>     $*PROGRAM.parent.parent.add("lib")

I'll take it under advisement that there might be some system out
there that can't deal with the unixism ".." (though my experience
is those are getting increasingly rare).

I might start doing something like this:


>> I thought that this would fix the problem, but I see the same
>> compile time error with it:
>>    BEGIN {
>>      my $lib_loc = $*PROGRAM.parent.add('../lib');
>>      use lib "$lib_loc";
>>    }
> Inside the BEGIN block, it's just the same: the variable is defined, but not
> initialized yet when the "use lib" is executed at compile time *inside* the
> BEGIN block.

Right, got it.  One of the reasons I was confused is I'd also
tried this:

   BEGIN {
     my $lib_loc = $*PROGRAM.parent.add('../lib');
   use lib "$lib_loc";

But there the trouble is the scope of the block.  This works:

   my $lib_loc;
   BEGIN {
     $lib_loc = $*PROGRAM.parent.add('../lib');
   use lib "$lib_loc";

As does the approach you suggest:

   BEGIN my $lib_loc = $*PROGRAM.parent.add('../lib');

> ... BEGIN as a prefix, so that it shares its scope with its
> surrounding scope.

And that's definitely a key advantage

> This is not different from Perl, BTW.

Yes, and as I remember it, I've gone through a similar set of
mistakes with Perl.

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About