Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I check if a parameter is a subroutine?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading