Executing Perl code inside a shell script using eval

Found the following example. I tried google but couldn't find much, so I post this question here.

  • What is the advantage of running a perl script like this?
  • How can we make a shell script run like a β€œnormal” shell script after executing Perl code?

Here is the code:

#!/bin/ksh #! -*- perl -*- eval 'exec $PERLLOCATION/bin/perl -x $0 ${1+" $@ "} ;' if 0; print "hello world\n"; # how can I make it behave like a "normal" shell script from this point onwards? What needs to be done? # echo "hello world" ### this results in error 
+1
source share
3 answers

1. If you run the Perl script in the usual way:

 #!/usr/bin/perl print "hello world\n"; 

line #! will only work if the Perl interpreter is actually installed in /usr/bin . The bilingual script perl / ksh that you show is a difficult task to make the script work, even if perl is installed somewhere else. For more information, see, for example, http://alumnus.caltech.edu/~svhwan/prodScript/invokingPerl.html

2. You cannot. When the shell process encounters the exec command, it exits, and hands are controlled by perl. (Technically, it executes perl instead of the shell without creating a new process .) The only way to run more shell commands after this is to start a new shell.

+1
source

This idiom is described in the perlrun documentation. The -x switch scans the entire file and ignores everything that appears before the first line starting with #! , and also contains the word perl . This means that your system will run the script using the Perl interpreter, whether you call the script using perl or using the shell command ( sh/bash/ksh/ etc.). I.e

 $ perl this_script 

and

 $ sh this_script 

both will run the script using perl .

To solve the second question, this idiom has nothing to do with combining the shell script and the Perl script in the same file. There are several ways to approach this problem, but perhaps the most readable way is to write a script in the shell, but using the shell's heredoc notation to invoke Perl code.

 #!/bin/bash # this is a bash script, but there is some Perl in here too echo this line is printed from the shell echo now let\ run some Perl perl <<EOF # this is now perl script until we get to the EOF print "This line is printed from Perl\n"; EOF echo now this is from the shell script again 
+5
source

This is easier than what has already been published.

 #!$PERLLOCATION/bin/perl 

does not work because the shebang ( #! ) string is interpreted by the kernel (not the shell), and the kernel does not perform interpolation variable.

The code calls ksh to deploy the environment variable and run the specified Perl installation.

+2
source

All Articles