Perl Subroutine Prototyping — The correct way to do it

后端 未结 5 1323
滥情空心
滥情空心 2020-12-10 06:48

I have a subroutine called debug I use in my code. It basically allows me to see what\'s going on, etc.

sub debug {
    my $message      = shift         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 07:19

    The prototype is attached to the coderef and not the name, so when you replace the coderef with the new declaration, you are clearing the prototype. You can avoid having to cross-reference and match prototypes with a helper function:

    sub debug ($;$);
    
    debug 'foo';
    
    use Scalar::Util 'set_prototype';
    sub install {
        my ($name, $code) = @_;
        my $glob = do {no strict 'refs'; \*$name};
        set_prototype \&$code, prototype \&$glob;
        *$glob = $code;
    }
    
    BEGIN {
        install debug => sub {
            print "body of debug: @_\n";
        };
    }
    

    install is just a wrapper around Scalar::Util's set_prototype function, which allows you to change the prototype of a coderef after it is created.

    Prototypes can be very useful, but when using the scalar prototype, always ask yourself if that is really what you intended. Because the ($;$) prototype tells perl "debug is a function that can take one or two arguments, each with scalar context imposed on the call site".

    The bit about context is where people usually get tripped up, because then if you try to do this:

    my @array = qw(one two);
    
    debug @array;
    

    Then @array gets seen in scalar context, and becomes 2. So the call becomes debug 2; rather than debug 'one', 'two'; as you might have expected.

提交回复
热议问题