Why am I getting “called too early to check prototype” warnings in my Perl code?

前端 未结 5 715
你的背包
你的背包 2021-02-07 13:01

I have a Perl file like this:

use strict;
f1();

sub f3()
{ f2(); }

sub f1()
{}
sub f2()
{}

In short, f1 is called before it is d

5条回答
  •  离开以前
    2021-02-07 13:38

    The lack of a warning on the call to f2() from f3() appears to be a bug.

    use strict;
    use warnings;
    
    f1();
    
    sub f1 {
        my @a = qw(a b c);
        f2(@a);
    }
    
    sub f2(\@) { print $_[0] }
    

    This prints "a". If you either predeclare f2() or swap the order of the subroutine definitions, it prints "ARRAY(0x182c054)".

    As for resolving the situation, it depends. My preferences (in order) would be:

    1. Remove the prototypes from the subroutine definitions. Perl's prototypes don't do what most people expect them to. They're really only useful for declaring subs that act like builtins. Unless you're trying to extend Perl's syntax, don't use them.
    2. Predeclare the subroutines before using them. This lets Perl know about the prototype before the encountering any calls.
    3. Reorder the code so that the subroutine definitions appear before any calls.
    4. Call the subroutines using the &foo() notation to bypass prototype checking.

提交回复
热议问题