system, backticks and pipes

system and $?

system runs a program, waits for it, and returns the status. Pass the command and its arguments as a list and no shell is involved; pass one string and the shell interprets it.

use strict; use warnings; my $status = system("ls", "-1", "/tmp"); if ($status == -1) { die "could not start ls: $!\n"; } elsif ($status & 127) { die "ls died from signal ", $status & 127, "\n"; } elsif ($status >> 8) { die "ls failed with exit code ", $status >> 8, "\n"; }

The raw return value packs two numbers: shift it right by eight for the exit code, mask it with 127 for the signal. Perl also copies it into $?, and $! holds the system error when the program could not be started at all.

A status of -1 means the fork or exec failed, which is different from the program running and returning an error. Treat the two cases separately, as above.

Capturing output

Backticks run the command and give you its standard output as a string. qx{} is the same operator in a form that reads better with quotes inside the command:

my $date = `date +%Y-%m-%d`; chomp $date; my @lines = qx{git log --oneline -5}; print "$_" for @lines;

In list context the output is split into lines with their newlines kept, which is usually what you want. In scalar context you get one string, so remember to chomp it before comparing.

Both backticks and the one-string form of system go through the shell, so a file name containing a space or a semicolon can change the meaning of the command. For real programs use the list form of open:

open my $fh, "-|", "git", "log", "--oneline", "-5" or die "cannot run git: $!\n"; while (my $line = <$fh>) { print $line; } close $fh or warn "git exited with ", $? >> 8, "\n";

Here the exit status arrives in $? when you close the handle, so check the close, not just the open.

Pipes both ways

open with "|-" creates a pipe into a program, so you can stream data to it instead of writing a file and passing the name:

open my $sort, "|-", "sort", "-n" or die "cannot start sort: $!\n"; print $sort "$_" for (30, 4, 200); close $sort;

4 30 200

The child prints to the terminal directly, because only its input is connected to you. When you need to control stdin and stdout at once, use IPC::Open3 from the standard library, or IPC::Run from CPAN, which wraps all three handles in one call.

use IPC::Open3; use Symbol 'gensym'; my $err = gensym; my $pid = open3(my $in, my $out, $err, "bc"); print $in "2 + 3\n"; close $in; print scalar <$out>; waitpid $pid, 0;

5

Shell safety

The rule is short: never put a value you did not write into a string that goes to the shell. A file named report; rm -rf ~ is a valid file name, and backticks will happily run both commands.

my $file = $ARGV[0]; system("wc", "-l", $file); # safe: no shell system("wc -l $file"); # unsafe

The list form passes each argument to the program unchanged, spaces included. If you genuinely need a shell feature, build the command yourself from validated parts and quote every interpolated value, or use String::ShellQuote.

Two more habits pay off. Check every return value, because a silent failure inside a pipeline is the hardest bug to find. And prefer exec when your script does nothing after starting a program: it replaces the current process, so signals and the exit code reach the caller directly.

exec("tail", "-f", $log) or die "cannot exec tail: $!\n";

Next: One-liners with -n and -p

Article author: Arthur Isaev