Perl parentheses

For historical reasons, Perl does not need parentheses when calling a function. It is recommended to use parentheses but there are many modules or even examples in the official Perl documentation where they are missing.

For me, it is one of the nicest things about Perl that parentheses are optional because I think it is easier to write and read without them.

Here is a short example of how a Perl script can look:

#!/usr/bin/perl

use strict;
use warnings;

open my $fh, "<", "/etc/passwd"
    or die "Can`t open file: $!";

while (<$fh>) {
    print $_;
}

close $fh;

In the example above we open a File. You can see that I did not use parentheses. After opening the file, I use the diamond operator <> with the file handle to read line by line from the file. Each line gets stored in the variable $_. $_ is the default variable from Perl and is used in many places. After printing each line the file handle gets closed.

Not using parentheses is a great thing but there are cases where it does not work as expected and that´s one reason why many people think they should be mandatory.

Here is a short example of one case that does not work:

#!/usr/bin/perl

use strict;
use warnings;

my @cmd = ("ls", "/tmp");

system @cmd == 0
    or die "Command failed: $!";

system (@cmd) == 0
    or die "Command failed: $!";

In this example, I want to run the UNIX Command ls and check if the Return Code is 0. If not, stop the script with an error. The Problem here is that Perl does not understand in which order it should execute the code and needs parentheses as seen in the second call to system.

The Perl module B::Deparse with the -p flag can be used to see what is going on.

perl -MO=Deparse,-p test.pl
# use strict;
# use warnings;
# (my(@cmd) = ('ls', '/tmp'));
# (system((@cmd == 0)) or die(("Command failed: $!")));
# ((system(@cmd) == 0) or die(("Command failed: $!")));
# test.pl syntax OK

In the Output, we see the 2 different lines. In the first Perl checks if @cmd is 0 and then runs system with the result, in the second one, Perl runs system with our command and checks if the command return code was 0.

I will continue to not use parentheses when I write Perl but now know that there are some problems with it and know a way how to debug them.

25 May 2024 - Philipp Keschl