Reputation: 7735
SaveImages @img_sources;
The above will report:
Array found where operator expected
Why can't I omit the ()
here?
Upvotes: 6
Views: 332
Reputation: 4048
You can omit ()
with built-in functions (see perlfunc) because built-in functions are keywords of the language and don't need parentheses to be recognized as functions.
Some imported functions (as max
from List::Util
), usually from core modules, may be called without parenthesis also.
If a subroutine is declared before being called, parentheses can be omitted too, although Perl Best Practices (chapter 2, section 4) recommends to avoid it in order to distinguish between calls to subroutines and built-ins.
Upvotes: -2
Reputation: 20280
Many good points here, just one more: see also the subs
pragma. Used like use subs qw/SaveImage/;
before your function call (probably near the top with the other use
calls) it should nicely predeclare your sub in a less obtrusive way.
Upvotes: 4
Reputation: 10234
Perl can parse calls to subroutines without parens when those have been previously declared (or defined). For instance:
sub SaveImages;
SaveImages @img_sources;
Upvotes: 6
Reputation: 13942
From perlsub:
To call subroutines:
NAME(LIST); # & is optional with parentheses. NAME LIST; # Parentheses optional if predeclared/imported. &NAME(LIST); # Circumvent prototypes. &NAME; # Makes current @_ visible to called subroutine.
Usually subs are not pre-declared in practice. That's not usually a problem, as people are generally accustomed to using parens with programmer-created subs.
Perl::Critic (A module that supports Damien Conway's model of Perltopia as set forth in Perl Best Practices) suggests the following treatments for subs:
One of the reasons for not using parens with built-ins is to make them visually distinct from program-defined functions, which traditionally DO use parens. Since it's unusual to predeclare subs, and it's discouraged to use ampersand (because it alters how @_ may be treated), or prototypes (because, well, it's a long story), that leaves a very strong background for using parens with script-defined subs.
Upvotes: 6
Reputation: 9436
because your SaveImages subroutine is declared after the call. Parentheses are not necessary if a subroutine is declared before the call.
example:
use strict;
use warnings;
use Data::Dumper;
my @ar = (1, 2);
fn @ar;
sub fn
{
print Dumper \@_;
}
does not work, while
use strict;
use warnings;
use Data::Dumper;
my @ar = (1, 2);
sub fn
{
print Dumper \@_;
}
fn @ar;
works.
This is an expected behavior and is pointed out in the camel book.
Upvotes: 13