http://www.perlmonks.org?node_id=226782


in reply to How to use dynamic execution path instead of absolut.

On Unix system the following should work:
#!/bin/sh `which perl` -x $0 $* exit #!perl print "hello perl\n";
which finds (hopefully) your perl.
The backticks execute the found perl.
The -x switch forces perl to skip everything before #!perl
$0 is the scriptname.
$* are all commandline parameters.

Replies are listed 'Best First'.
Re^2: How to use dynamic execution path instead of absolut.
by Aristotle (Chancellor) on Jan 14, 2003 at 10:41 UTC
    `which perl` -x $0 $*
    That's a useless use of backticks. which will only find something which is in the PATH, and then shell can find it as well, so you can just rephrase that as perl -x $0 $* That reminds me - perlrun has the following snippet:
    #!/bin/sh eval 'exec perl -S $0 ${1+"$@"}' if $running_under_some_shell; # regular perl code follows here
    If you really want, you can also put switches for Perl at the end of the shebang line if it looks like so: #!/bin/sh -- # -*- perl -*- -wT

    Makeshifts last the longest.

      That's a useless use of backticks. which will only find something which is in the PATH, and then shell can find it as well, so you can just rephrase that as

      perl -x $0 $*

      Arrgh! You're absolutly right!

•Re: Re: How to use dynamic execution path instead of absolut.
by merlyn (Sage) on Jan 14, 2003 at 17:44 UTC
    Besides the useless use of backticks pointed out in another subthread, this is also dangerous code:
    `which perl` -x $0 $*
    What if I invoked this script as:
    yourscript "randal l." schwartz
    I've just passed two parameters, but your reinvocation is going to give three parameters to the Perl program.

    Quoting matters. The example in perlrun is very carefully constructed to avoid quoting problems.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.