A custom way to call routines in Perl

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

I have a feature set as follows:

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

Then I look at the 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 Testcase_CheckStatus function, as shown above, when analyzing the hash keys, but I get this error:

Cannot find the method of the object "Testcase_" through the package "CheckStatus" (maybe you forgot to download "CheckStatus"?) In. /main.pl line 17

What can I do to fix this problem? Is there an alternative way to do the same?

+3
source share
2 answers

The following should allow you to do what you want:

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

, strict. strict, no strict while, :

while (my ($k, $v) = each %test_cases) {
    no strict 'refs';

    print "TestCase_$k","\n";
    &{"Testcase_$k"}();
}
+6

:

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

All Articles