in reply to New Discovery!!! (sub call without parentheses)
I always use parens when calling user-defined subroutines and methods because:
- The consistency of always using parens when calling user-defined subroutines/methods makes the code easier to read (for me).
- The code is more robust when reorganized. For example, if you later switch from use (compile-time) to require (run-time) -- to speed initial module load or when porting to a new platform, say -- your code may break in surprising ways. Even if you can "easily" fix the code to use parens (so that it will parse correctly with require), doing so risks breaking what might be thousands of lines of working production code ... so avoid that future pain by always using parens in the first place.
As a matter of style, some folks find the code easier to read when user-defined functions are always called with parens and built-in functions always called without parens. Perl Best Practices endorses this style:
- Don’t use unnecessary parentheses for builtins and ‘honorary’ builtins (item 4)
- Call subroutines with parentheses but without a leading & (item 113)
Note that:
use SomeModule (); is equivalent to: require SomeModule;
while:
use SomeModule; is equivalent to: require SomeModule; SomeModule->import();
with use performed at compile time, require at run time. See perlmod for details.
References Added Later
- As pointed out by choroba here, when the Perl compiler sees the parens while parsing, it deduces that it is a subroutine call, even before it has seen the subroutine definition ... while without parens, a strict compile fails because the function name is an unrecognized bareword (Bareword "SomeFn" not allowed while "strict subs" in use).
- For static parseability, parser toolkit Guacamole's standard mandates "All subroutines must use parentheses" (see also Re^8: poll ideas quest 2021).
- Indirect Object Syntax (from perldoc perlobj) - see also Indirect Object Syntax by Bod from (working class) Coventry, UK (though he hails from posh Warwick).
- Re^2: Correct keys in hashes by Aristotle - who notes that $foo{name} is always interpreted as $foo{'name'} and you need $foo{name()} to indicate a function call ... and you should get in the habit of never calling functions without parens.
See Also
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: New Discovery!!! (sub call without parentheses)
by stevieb (Canon) on Dec 08, 2018 at 23:00 UTC | |
by LanX (Saint) on Dec 09, 2018 at 00:28 UTC | |
Re^2: New Discovery!!! (sub call without parentheses)
by LanX (Saint) on Dec 08, 2018 at 19:25 UTC |
In Section
Seekers of Perl Wisdom