I would like to check if a subroutine exists before calling it. For example:
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. It gives 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 fine, but it would be nice to know why the first code did not work?
You're trying to make a reference before knowing whether or not the sub exists. Check that first using the name of the subroutine in the call to exists
.
use strict;
use warnings;
foreach (qw(A B)) {
my $name = 'print' . $_;
if (exists &{$name}) {
my $s = \&{$name};
$s->();
}
}
sub printA {
print "hello A"
}
my $sub = main->can("print$_");
if ($sub) {
$sub->();
}
From perldoc
can checks if the object or class has a method called METHOD . If it does, then it returns a reference to the sub. If it does not, then it returns undef. This includes methods inherited or imported by $obj , CLASS , or VAL .
if you change the code to:
for (@names) {
my $sub="print$_";
no strict 'refs';
if (exists &{$sub}) {
&$sub;
}
}
The method will call only if it exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With