Search code examples
perlsubroutine

Non standard way of calling sub-routines in Perl


I am trying a different way of calling a subroutine in a Perl script.

I have a set of functions as follows:

sub Testcase_CheckStatus {
    print "TestCase_CheckStatus called\n";
}

Then I'm traversing a Perl hash with keys like "CheckStatus":

while (my ($k, $v) = each %test_cases) {
    print "TestCase_$k","\n";
    Testcase_$k();
}

Basically, I want to call the function Testcase_CheckStatus like above while parsing the keys of hash, but I'm getting this error:

Can't locate object method "Testcase_" via package "CheckStatus" (perhaps you forgot to load "CheckStatus"?) at ./main.pl line 17

What can I do to correct this problem? Is there any alternate way of doing the same?


Solution

  • The following should allow you to do what you want:

    while (my ($k, $v) = each %test_cases) {
        print "TestCase_$k","\n";
        &{"Testcase_$k"}();
    }
    

    However, this won't work if strict is in use. If you are using strict you will need a no strict inside the while loop, e.g.:

    while (my ($k, $v) = each %test_cases) {
        no strict 'refs';
    
        print "TestCase_$k","\n";
        &{"Testcase_$k"}();
    }