When should I use Perl's AUTOLOAD?

前端 未结 3 1521
我在风中等你
我在风中等你 2021-01-17 17:13

In \"Perl Best Practices\" the very first line in the section on AUTOLOAD is:

Don\'t use AUTOLOAD

However all t

相关标签:
3条回答
  • 2021-01-17 17:42

    I think for a stand alone script this approach is OK. You can create subroutines on the fly to speed up subsequent calls, e.g.:

    sub AUTOLOAD {
        (my $name = our $AUTOLOAD) =~ s/.*:://;
        no strict 'refs';  # allow symbolic references
    
        *$AUTOLOAD = sub { print "$name subroutine called\n" };    
        goto &$AUTOLOAD;   # jump to the new sub
    }
    

    Autoloading is tricky when producing inheritance trees.

    0 讨论(0)
  • 2021-01-17 17:50

    An alternative strategy would be to write the script as an App::* module and have the commandline option choose which class to load to provide whatever functionality it is that's pluggable depending on the option. You would require that class just-in-time once you know which it is. It's a little more up-front work, but if you intend to maintain the script for a long time, I bet it would pay off. The past couple years have seen the creation of some extra-nice tools for creating scripts whose functionality really lives in modules, including App::Cmd, MooseX::Getopt, and the bastard offspring of both.

    0 讨论(0)
  • 2021-01-17 17:54

    If your only reason for using AUTOLOAD is to relocate the block to the end, why not put it at the end in a subroutine, and then call it as soon as its dependent variables are defined?

    sub tcpdump;  # declare your subs if you want to call without parens
    
    # define the parameters
    
    compile();
    
    # code that uses new subs
    
    sub compile {
        *tcpdump = $tcpdump ? sub {
            my $msg = shift;
            warn gf_time()." Thread ".threads->tid().": $msg\n";
        } : sub {};
        # ...
    }
    # EOF
    

    Better still, if the globals aren't needed elsewhere, just pass the values to compile as arguments.

    0 讨论(0)
提交回复
热议问题