How can I test if a given parameter is a subroutine?
For example:
sub foo {
my $bar = shift;
if (is_subroutine($bar)) {
return &$bar();
}
return 0;
}
I’d call this like:
foo(sub { print "Hi!" }); # prints "Hi!"
foo(123); # Nothing
How can I do this?
>Solution :
You can try to dereference the scalar as a subroutine with &{...} and then check if the result exists.
if (exists &{$bar}) {
...
}
Also, $bar() is not valid syntax for calling a subroutine stored in a scalar reference. You’ll need to write either &{$bar}() or $bar->() (the latter is sugar for the former)