Your first Perl script

The file

A Perl program is a text file with a .pl extension, though nothing forces the name. Create hello.pl and put four lines in it: a shebang, the two pragmas every modern file starts with, and one print.

Create the script

vi hello.pl

#!/usr/bin/perl use strict; use warnings; print "Hello, world\n";

The first line is the shebang: it names the interpreter that should run the file when you execute the file directly. On systems where perl lives elsewhere, #!/usr/bin/env perl is the portable form.

strict and warnings

use strict turns three common mistakes into errors: undeclared variables, barewords that look like functions, and string references used as symbolic ones. use warnings adds advice about suspicious code, such as a numeric comparison against text that never looks numeric.

Together they cost two lines and save hours. Add them to every file you write, including one-off scripts that you plan to delete tomorrow - those are the ones that survive for years.

Run it

Hand the file to the interpreter by name. No build step, no output folder: the program runs and prints one line.

perl hello.pl

Hello, world

If the shell answers Can't open perl script, you are in the wrong folder. Change into the directory that holds hello.pl and try again.

Make it executable

With the shebang in place, the file can run like any other command. Grant the execute bit once, then call it by name:

chmod +x hello.pl

./hello.pl

Hello, world

The leading dot and slash are required: without them the shell looks for hello.pl in the folders listed in PATH, not in the current one. That rule is the same for every script you will write in this course.

Next: The debugger as a REPL

Article author: Arthur Isaev