Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

problem with INC

by Anonymous Monk
on Jan 21, 2004 at 16:09 UTC ( #322920=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

hello monks , I have this small code :
#!/usr/local/bin/perl my $dir = "/home/user/scripts"; push (@INC, $dir); use kp1; sub num1 { kp1::hello (8); } &num1;
I am running the script from /home/user/scripts/myscripts which is one level lower than the directory containing kp1 but every time I run it , i get an error saying it can't use or find kp1 even though I put the correct path for $dir where the kp1 sits , any idea? thanks

Replies are listed 'Best First'.
Re: problem with INC
by ysth (Canon) on Jan 21, 2004 at 16:14 UTC
    The push(@INC...) happens when your script is running, but the use kp1 happens at compile time, when @INC is not yet set. Two ways to fix it:
    # make sure not to use a variable that is only set at run time BEGIN { push (@INC, "/home/usr/scripts"); } use kp1;
    use lib "/home/usr/scripts"; use kp1;
Re: problem with INC
by broquaint (Abbot) on Jan 21, 2004 at 16:18 UTC
    Because use is evaluated at compile-time you need to modify @INC before a given use statement is reached. Handily perl comes with the lib module to facilitate such @INC munging e.g
    ## this will modify @INC before the next 'use' statement use lib "/home/user/scripts"; use kp1;
    Also note that I didn't use the lexical variable $dir as that will be declared at compile-time but won't be initialized until run-time (although you can get around this by using a BEGIN block).


Re: problem with INC
by blue_cowdawg (Monsignor) on Jan 21, 2004 at 16:18 UTC

    You can try

    use lib "/home/user/scripts";
    BEGIN{ push @INC,"/home/user/scripts";}
    Of course, you want to make sure that /home/user/scripts is a valid path at run-time...

    To be quite honest I prefer the first method over the second one and haven't used a BEGIN block in a very long time.

    Peter L. Berghold -- Unix Professional
    Peter at Berghold dot Net
       Dog trainer, dog agility exhibitor, brewer of fine Belgian style ales. Happiness is a warm, tired, contented dog curled up at your side and a good Belgian ale in your chalice.
Re: problem with INC
by tcf22 (Priest) on Jan 21, 2004 at 16:14 UTC
    use lib.
    #!/usr/local/bin/perl use lib "/home/user/scripts"; use kp1;
    Update: Fixed use of variable in use lib.

    - Tom

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://322920]
Approved by blue_cowdawg
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2023-01-28 17:31 GMT
Find Nodes?
    Voting Booth?

    No recent polls found