'I wanted to call function which is coming in another function as an argument, but getting error [closed]

I have a function which is calling another function and passing arguments in it. where one of the argument is the function which is store in variable. when I am trying to call that function in another function it is throwing an error.

my @tst1 = ("tst1 - Checking Whether the naming format of created Directory by using tar ball is same as expected in the format of trustid_web_ yyyyMMdd-HHmmss.tar.gz and same as tar ball", "runCmd()");
@tstInfo = (\@tst1);

sub populatetestCb() {   
    for ($i = 0; $i <= $ #tstInfo; $i++) {
        $testCb {
            $i + 1
        } = $tstInfo[$i];
    }
}

populatetestCb();
$startTime = localtime();
my $tmp = 1;

while (1) {
    my $ret = getTestDetails($tmp);
    if ($ret eq 1) {
        $tStartTime = localtime();
        my $tstRes = runTest($tstDes, $tstFunction);
        $tEndTime = localtime();
        #PRINT_LOG("runTest returned $tstRes\n");
        $tmp++;
        sleep(2);
    } else {
        last;
    }
}

sub runTest {
    $tstName = $_[0];
    my $tstFunction = $_[1];
    print($tstFunction);
    my $action = \ & $tstFunction;
    $action - > ();
}

when I am calling $action->() in my runTest function it is throwing

Undefined subroutine &main::runCmd() called at testAutomation.pl line 83. 

my @tst1 is the array which consists test Description and the function needed to call to test it. populateTestCb is the hash which is storing it and I am accessing it in getTestDetails function from where I wanted to call runTest and call particular function into it.



Solution 1:[1]

Without strict, calling function by name normally works:

no strict;

my $name = 'func';
$name->() and print 'ok';  # ok

sub func { 1 }

Under strict, it's still possible, but needs an extra step. It shouldn't be used for anything but AUTOLOAD, though.

my $name = 'func';
my $f = \&{$name};
$f->() and print 'ok';  # ok

Normally, you'd store a subroutine reference in a variable and call it later:

my $func = \&func;
$func->() and print 'ok';  # ok

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 choroba