How to execute (run) a Perl script

A Perl script is nothing but a plain text file. By itself it will do nothing. The script needs the Perl interpreter in order to execute the code that it contains. The Perl interpreter will open the file, read it line by line, check the syntax of the code, and, if everything was done correctly according to the rules of the language, execute the code.

Invoking the Perl Interpreter on the Command Line

Let us assume we have written a Perl script, called 'my_script.pl', which is located in the current working directory. The script consists of only one line:

print "Hello, world!\n";

In order to run the script we enter the following on the command line,

perl ./my_script.pl

and the 'Hello, world!' message should appear on the screen.

Making the Script Executable

On Unix systems there exists a convention by which scripts can configured to run just like an executable program. If this is done, only the script's name needs to be entered on the command line. This is sometimes necessary so that other programs, like a web server, can run scripts.

Two things are necessary in order to make a script executable:

First, the Unix system has to know where the Perl interpreter is located. By convention, this is done by including the path to the Perl interpreter in the first line of the script. The path must be preceded by a pound sign and exclamation mark, #!.

If you don't know where the Perl interpreter is located on the system you are working on, enter

which perl

on the command line. On the CS network the result should look like this:

/usr/local/bin/perl

Now put the pound sign, exclamation mark, and the path to the interpreter in the first line of your script, which should look like this now:
#!/usr/local/bin/perl

print "Hello, world!\n";

Save the script and exit the text editor.

Second, you have to tell the operating system that your script can be executed. Enter the following on the command line:

chmod +x ./my_script.pl

chmod (change mode) adds the execution bit (+x) to the the file's permissions (see also Setting permissions for an alternative version). If this succeeded, you should be able to enter

./my_script.pl

on the command line and the script should execute.