I would like to check if a subroutine exists before calling it. For instance:
use warnings;
use strict;
my @names=qw (A B);
for (@names) {
my $sub=\&{"print$_"};
if (exists &{$sub}) {
&$sub();
}
}
sub printA {
print "hello A\n";
}
However, this code does not work. This gives an error:
Undefined subroutine &main::printB
I know that I can use eval,
for (@names) {
my $sub=\&{"print$_"};
eval {
&$sub();
};
if ($@) {
print "$_ does not exist..\n";
}
}
This is great, but it would be nice to know why the first code didn't work?
source
share