Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

New Discovery!!! (sub call without parentheses)

by harangzsolt33 (Chaplain)
on Dec 08, 2018 at 02:19 UTC ( [id://1226936]=perlquestion: print w/replies, xml ) Need Help??

harangzsolt33 has asked for the wisdom of the Perl Monks concerning the following question:

I have noticed something very interesting!!! When I declare a sub, then I can call that sub without parentheses, but if I want to call that sub before the declaration, then I need to use parentheses. Why is that???? I mean what's the logic behind this behavior?

MyFunc(4, 5); sub MyFunc { print "Hello World!! :) @_ \n"; } MyFunc 3, 2;

If I flipped this around, then I'd get an error, but I don't understand why...:

MyFunc 3, 2; sub MyFunc { print "Hello World!! :) @_ \n"; } MyFunc(4, 5); # This program won't run! :(

Replies are listed 'Best First'.
Re: New Discovery!!! (sub call without parentheses)
by kschwab (Vicar) on Dec 08, 2018 at 02:48 UTC

    It's documented in perlsub. See the note about "if predeclared" below...

    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.

    Probably just an artifact of a parser that uses a single pass. Can't disambiguate something you haven't seen yet.

Re: New Discovery!!! (sub call without parentheses)
by LanX (Saint) on Dec 08, 2018 at 03:58 UTC
    To catch typos.

    Perl is dynamic enough to allow calling subs which are not pre declared.

    I.e. not known at the time of parsing the call.

    NB the sub doesn't even need to be declared in the same file.

    And if the sub is missing you'll get a run time error.

    To avoid ambiguity you need to be explicit that you are calling a sub.

    Languages like Ruby allow dynamic subs without brackets, because a simple bare word isn't allowed to be a string there (like in non strict Perl)

    See also use subs and strict#strict-subs

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

    edit

    I think it's an effect of Perl4's design, where bare words could be strings and &subs needed a sigil.

      This little demo in the debugger (without strict) should make it clearer

      DB<5> print "x".NAME # bareword treated as string xNAME DB<6> sub NAME {42} # sub declaration DB<7> print "x".NAME # bareword now known to be s +ub x42 DB<8> print "x".NAME2() # explicit sub call Undefined subroutine &main::NAME2 called at (eval 17)[C:/Perl_524/lib/ +perl5db.pl:737] line 2. DB<9> print "x".&NAME2 # explicit sub call Undefined subroutine &main::NAME2 called at (eval 18)[C:/Perl_524/lib/ +perl5db.pl:737] line 2. DB<10>

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

      Perl is dynamic enough to allow calling subs which are not pre declared. I.e. not known at the time of parsing the call.

      Is "dynamic" here used as a notion of "smart enough to understand by itself where to go look for things before exploding at run-time"? Because even in Java and C, which aren't "dynamic" in the classic sense of languages in which you must (statically) declare each variable/object type at compile time, you can do the same thing, e.g.: in Java you can call a method declared at the bottom of the class.

      There are difference in the way the compilation phase is carried out for these languages, but they generally tend to process the entire "compilation unit" when they are building the parse tree (or whatever they call it), so they can understand reference to functions wherever they are defined (C for example halts you at linking phase if it can't find the relative object). I think Perl does a similar thing when you call a sub() defined at the end of a module to avoid exploding during the compilation(somebody would say interpretation in strict terms) phase.

      This is not the case for Python, which stops if the token(function name) is unknown(NameError) during parsing.

        > Is "dynamic" here used as a notion of "smart enough to understand by itself where to go look for things before exploding at run-time"?

        dynamic in the sense of not exploding at compile-time.

        > I think Perl does a similar thing

        not really?

        Perl looks at runtime into the symbol table of the package. I wouldn't call this linking, but I'm no C expert.

        DB<10> func() Undefined subroutine &main::func called at (eval 19)[C:/Perl_524/lib/p +erl5db.pl:737] line 2. DB<11> eval { sub func {} } # created at run-time DB<12> func() DB<13> p \&main::func # STASH entry CODE(0x58443b8) DB<14>

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Re: New Discovery!!! (sub call without parentheses) - Coding Style
by eyepopslikeamosquito (Archbishop) on Dec 08, 2018 at 17:46 UTC

    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

      Two very good points there.

      I always use parens on my user-defined functions whether I've got parameters or not. Kind of a habit actually now that I'm fluent in more than just a couple of languages, most of which enforce using parens. In fact, thinking about it, I think Perl's the only language which *doesn't* enforce parens if a function is pre-declared. Also, at a glance (at least with my own code), it's easier to identify built-ins, as I typically don't use parens for them (eg: sleep 10;).

      The only time I'll leave parens off of a call, is if it's a method call where I'm not sending in any params:

      my $object = My::Thing->new(speak => 'hi'); ... $object->speak;
        > I think Perl's the only language which doesn't enforce parens if a function is pre-declared

        Ruby never does, but probably you wanted to say "if and only if" ?

        The possibility to omit parenthesis is essential for many syntactic sugar and DSL approaches.

        Compare "has" in Moose which looks like a keyword.

        update

        example

        has 'first_name' => ( is => 'rw', isa => 'Str', );

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

      Yes, but with exceptions.

      When designing syntactic sugar and/or DSLs its useful to leave the parentheses off.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1226936]
Approved by Athanasius
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (2)
As of 2024-04-26 03:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found