When should I use Perl's AUTOLOAD?
Posted
by Robert S. Barnes
on Stack Overflow
See other posts from Stack Overflow
or by Robert S. Barnes
Published on 2010-03-17T08:43:25Z
Indexed on
2010/03/18
2:41 UTC
Read the original article
Hit count: 564
In "Perl Best Practices" the very first line in the section on AUTOLOAD is:
Don't use AUTOLOAD
However all the cases he describes are dealing with OO or Modules.
I have a stand alone script in which some command line switches control which versions of particular functions get defined. Now I know I could just take the conditionals and the evals and stick them naked at the top of my file before everything else, but I find it convenient and cleaner to put them in AUTOLOAD at the end of the file.
Is this bad practice / style? If you think so why, and is there a another way to do it?
As per brian's request
I'm basically using this to do conditional compilation based on command line switches.
I don't mind some constructive criticism.
sub AUTOLOAD {
our $AUTOLOAD;
(my $method = $AUTOLOAD) =~ s/.*:://s; # remove package name
if ($method eq 'tcpdump' && $tcpdump) {
eval q(
sub tcpdump {
my $msg = shift;
warn gf_time()." Thread ".threads->tid().": $msg\n";
}
);
} elsif ($method eq 'loginfo' && $debug) {
eval q(
sub loginfo {
my $msg = shift;
$msg =~ s/$CRLF/\n/g;
print gf_time()." Thread ".threads->tid().": $msg\n";
}
);
} elsif ($method eq 'build_get') {
if ($pipelining) {
eval q(
sub build_get {
my $url = shift;
my $base = shift;
$url = "http://".$url unless $url =~ /^http/;
return "GET $url HTTP/1.1${CRLF}Host: $base$CRLF$CRLF";
}
);
} else {
eval q(
sub build_get {
my $url = shift;
my $base = shift;
$url = "http://".$url unless $url =~ /^http/;
return "GET $url HTTP/1.1${CRLF}Host: $base${CRLF}Connection: close$CRLF$CRLF";
}
);
}
} elsif ($method eq 'grow') {
eval q{ require Convert::Scalar qw(grow); };
if ($@) {
eval q( sub grow {} );
}
goto &$method;
} else {
eval "sub $method {}";
return;
}
die $@ if $@;
goto &$method;
}
© Stack Overflow or respective owner