Why is parenthesis optional only after sub declaration?

后端 未结 4 1136
栀梦
栀梦 2020-12-05 23:40

(Assume use strict; use warnings; throughout this question.)

I am exploring the usage of sub.

sub bb { print @_; }         


        
4条回答
  •  误落风尘
    2020-12-05 23:46

    The best answer I can come up with is that's the way Perl is written. It's not a satisfying answer, but in the end, it's the truth. Perl 6 (if it ever comes out) won't have this limitation.

    Perl has a lot of crud and cruft from five different versions of the language. Perl 4 and Perl 5 did some major changes which can cause problems with earlier programs written in a free flowing manner.

    Because of the long history, and the various ways Perl has and can work, it can be difficult for Perl to understand what's going on. When you have this:

    b $a, $c;
    

    Perl has no way of knowing if b is a string and is simply a bareword (which was allowed in Perl 4) or if b is a function. If b is a function, it should be stored in the symbol table as the rest of the program is parsed. If b isn't a subroutine, you shouldn't put it in the symbol table.

    When the Perl compiler sees this:

    b($a, $c);
    

    It doesn't know what the function b does, but it at least knows it's a function and can store it in the symbol table waiting for the definition to come later.

    When you pre-declare your function, Perl can see this:

    sub b;   #Or use subs qw(b); will also work.
    
    b $a, $c;
    

    and know that b is a function. It might not know what the function does, but there's now a symbol table entry for b as a function.

    One of the reasons for Perl 6 is to remove much of the baggage left from the older versions of Perl and to remove strange things like this.

    By the way, never ever use Perl Prototypes to get around this limitation. Use use subs or predeclare a blank subroutine. Don't use prototypes.

提交回复
热议问题