Home > Software design >  Perl variable subroutine name
Perl variable subroutine name

Time:04-14

Want to call a function in a variable subroutine name, like that :

use subrest1;
use subrest2;
use subrest3;
$SUB = "subrest1";

Tried :

($OK,$MSG) = \&$SUB::Test_Ldev($LDEVID);

Returns me the following message :

Undefined subroutine &main:: called

Where is my error ?

CodePudding user response:

Not pretty, but shortest:

($OK,$MSG) = do { no strict 'refs'; &{"${SUB}::Test_Ldev"}($LDEVID) };

Or so it works with strict, you can make a dispatch table, but the repetition isn't pretty either.

use subrest1;
use subrest2;
use subrest3;
my %SUBS = (
    subrest1 => \&subrest1::Test_Ldev,
    subrest2 => \&subrest2::Test_Ldev,
    subrest3 => \&subrest3::Test_Ldev,
);
my ($OK,$MSG) = $SUBS{$SUB}->($LDEVID);

Or you can combine the two and make the table dynamically:

my %SUBS = map { ( "subrest$_" => do {
        no strict 'refs'; \&{"subrest${_}::Test_Ldev"}
    } ) } 1..3;

(But I think the best would be if you didn't have three subtest modules in the first place...)

CodePudding user response:

The cleanest solution is to convert the various Test_Ldev subs into class methods. This is done by allowing for an extra argument.

sub Test_Ldev { 
   my ( $class, $LDEVID ) = @_;
   ...
}

Then the call becomes the following:

my ( $OK, $MSG ) = $SUB->Test_Ldev( $LDEVID );
  • Related