Parenthesise function calls

coding style Mon 15 April 2013

There are a number of things that jar with me slightly about the common perl coding style. One of them is the apparent desire to write code that reads like a sentence, and one specific part of that is determination to not parenthesise function parameters.

Here's an example I saw recently:

use String::Util qw(trim);
printf "<%s>\n", trim $z, right => 0;

I don't like this because code should be written for ease of comprehension, and my brain first scans that second line as:

printf A, B, C;

And trim looks like it's being used as an operator, rather than a function. To me trim is a function, not an operator. Ok, I admit it, this is a pretty blurred line, since printf() is a function, but very few people parenthesise printf, including me.

I parenthesise most functions, including all core functions that feel like functions. Picking some random code from site_perl:

open my $fh, '<', $file or die "$file: No such file";

Again, my brain chunks this wrongly, seeing $file or die as a unit.

If I wasn't using autodie, I'd write that as:

open(my $fh, '<', $file) || die "can't read $file: $!\n";

This point is addressed in Perl Best Practices, on page 13. Damian says that built-in functions are effectively keywords of the language, so "can legitimately be called without parentheses, except where it's necessary to enforce precedence". He claims that omitting the parentheses "reduces clutter in your code, and thereby enhances readability". Here's the key part of his example:

my ($name, $votes) = split "\t", $record;
print 'Votes for ', substr($name, 0, 10), ": $votes (verified)\n";

No parens with split, but parens are needed with substr for precedence. I would put parens around the split. I don't think you should rely on understanding of precedence for correct reading of code.

Maybe this betrays what programming language I used a lot before I switched to Perl for most tasks? That was a long time ago mind you.

comments powered by Disqus