http://qs321.pair.com?node_id=322920

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 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).
    HTH

    _________
    broquaint

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;
    or
    use lib "/home/usr/scripts"; use kp1;
Re: problem with INC
by blue_cowdawg (Monsignor) on Jan 21, 2004 at 16:18 UTC

    You can try

    use lib "/home/user/scripts";
    or
    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