Writing Your First Perl Script
Turn Perl into a real command-line tool: the shebang line, reading arguments and standard input, and making your script executable.
- perl
- scripting
- cli
- beginner
A one-off program is fine, but the point of Perl is small, reusable tools. This walks through building one.
The shebang line
The first line tells the system how to run the file:
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
#!/usr/bin/env perl finds Perl wherever it lives on the machine — more portable than hard-coding a path.
Reading command-line arguments
Arguments arrive in the special array @ARGV:
my ($name) = @ARGV;
$name //= "world"; # default if none given
say "Hello, $name!";
Run it:
perl greet.pl Ada # Hello, Ada!
perl greet.pl # Hello, world!
Reading standard input
To process piped input or a file line by line, read from the <STDIN> diamond:
while (my $line = <STDIN>) {
chomp $line; # remove the trailing newline
say "got: $line";
}
cat names.txt | perl greet.pl
A complete, useful example
A script that counts non-blank lines in whatever you pipe to it:
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my $count = 0;
while (my $line = <STDIN>) {
next if $line =~ /^\s*$/; # skip blank lines
$count++;
}
say "$count non-blank lines";
Making it executable
So you can run it directly instead of typing perl each time:
chmod +x count.pl
./count.pl < notes.txt
Where to go next
Learn to open and write files properly in Working with Files and I/O, and compress whole scripts into Perl One-Liners.