The Shell Script Method
The shell script method uses a shell script to start Perl. The way you do this is to put the following lines at the beginning of your program:
#!/bin/sh eval 'exec perl x -S $0 ${1+"$@"}' if 0; #!/usr/local/bin/perl
Now this code takes a little explaining. The code is bilingual in that it is a perfectly valid shell script and perl program.
Let's start by looking at the thing as a shell script. The first line tells the system that this is a shell (/bin/sh) script.
#!/bin/sh
The next line tells the shell to execute the perl command with the x and S options. The $0 variable is the name of the program and ${1+"$@"} is a magic string that passes the command line arguments from the shell to the perl command. (See your shell documentation if you are really interested in the details.)
eval 'exec perl x -S $0 ${1+"$@"}'
The exec command causes the shell to execute the specified command (perl) and never return. Since it never returns, the stuff that follows is never read by the shell.
There are two options passed to the perl program. The S $0 tells Perl to search for a script named $0 (the shell variable for the program name) along your path and to begin executing that script. The other option, x, tells Perl that the program is embedded in another script (such as shell script). The x flag tells Perl to skip all the garbage at the beginning and look for a magic string to start the program. In this case we use the magic string:
#!/usr/local/bin/perl
Note that this line works even if Perl is not installed in /usr/local/bin.
Running the Script Directly
Now let's take a look at what happens if we run the program using the command:
$ perl script.pl
The first line is:
#!/bin/sh
This line starts with a # so that Perl thinks it's a comment.
The next statement is:
eval 'exec perl x -S $0 ${1+"$@"}' if 0;
This is a valid Perl statement that tells Perl to execute a program, but only if the if condition is true. The if condition is 0, so it's never true. This is a long winded way of doing a nop.
The following line also starts with a #, so it too is treated as a comment.
#!/usr/local/bin/perlThe result of all this magic is that if you run the script directly, all the shell stuff is inert and does not affect the program.