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 "$_\n" for (30, 4, 200); close $sort;
perl demo.pl
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;
perl demo.pl
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";
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
systemreturn when the program runs and exits with code 0?Answer
The packed status, which is 0 for a clean exit
The return value and
$?hold the packed status, whose low bits are the signal and whose high bits are the exit code. -
How do you get the exit code out of the value
systemreturned?Answer
Shift it right by eight bits
The high byte is the exit code; the low seven bits name the signal that killed the program, if one did.
-
What does a
systemreturn value of -1 mean?Answer
The fork or exec failed, so the program never started
That case is different from a program that ran and reported an error, and
$!holds the reason. -
What do backticks give in list context and in scalar context?
Answer
The output split into lines in list context, one string in scalar context
The list form keeps the newlines on each line, and the scalar form needs a chomp before a comparison.
-
Why is
system("wc", "-l", $file)safer thansystem("wc -l $file")?Answer
The list form starts the program directly, so the shell never interprets the file name
Spaces and semicolons in a file name are data to the list form and shell syntax to the one-string form.
-
What does
execdo thatsystemdoes not?Answer
It replaces the current process, so nothing after it runs
The new program takes over the process, so its signals and exit code reach the caller directly.
-
What does this program print?
my $status = system("perl", "-e", "exit 3"); print $status >> 8, "\n";Answer
3
The child exits with 3, and the shift turns the packed status back into that number.
-
What does this program print?
my @lines = qx{printf "a\nb\n"}; print scalar @lines, "\n";Answer
2
List context splits the output into lines, and printf writes two of them.
-
What does this program print?
open my $fh, "-|", "printf", "one\ntwo\n" or die "open: $!"; my @lines = <$fh>; close $fh; print scalar @lines, "\n";Answer
2
The pipe runs printf without a shell, and the two lines it writes are read as two items.
-
What does this program print?
open my $fh, "-|", "perl", "-e", "exit 7" or die "open: $!"; my @out = <$fh>; close $fh; print $? >> 8, "\n";Answer
7
The status of the child arrives when the handle is closed, which is why the close is checked.
Article author: Arthur Isaev