vaibhav3002
vaibhav3002

Reputation: 275

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?

Upvotes: 3

Views: 186

Answers (2)

w.k
w.k

Reputation: 8376

Other way:

use 5.010;
use warnings;
use strict;


my $testcases = {
    test_case_1 => sub {
        return 1 * shift();
    },
    test_case_2 => sub {
        return 3 * shift();
    },
    test_case_3 => \&SomeSub,
};

for (1 .. 3) {
    say $testcases->{ 'test_case_' . $_ }(7);
}


sub SomeSub {
    return 5 * shift();
}

Upvotes: 13

mttrb
mttrb

Reputation: 8345

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"}();
}

Upvotes: 6

Related Questions