0

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 ?

4
  • What is the actual value of the variable? What sub are you trying to call? Commented Apr 13, 2022 at 9:03
  • $SUB = "subrest1"; Commented Apr 13, 2022 at 9:08
  • Are you trying to do the equivalent of calling subrest1($LDEVID) or subrest1::Test_Ldev($LDEVID), or what? Commented Apr 13, 2022 at 9:56
  • I want to call subrest1::Test_Ldev($LDEVID) or subrest2::Test_Ldev($LDEVID) depending on the value contained in $SUB which can be subrest1 or subrest2 (or subrestn) in the program Commented Apr 13, 2022 at 9:58

1 Answer 1

4

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 );
Sign up to request clarification or add additional context in comments.

4 Comments

Made the change for this sub in my subrest1 but when calling, got this error : Can't locate object method "Test_Ldev" via package "subrest1" (perhaps you forgot to load "subrest1"?), The perl module subrest1 is loaded (used successfully by another sub in another part of my main program)
Sounds like you didn't use the right package statement in subrest1.pm. It should be package subrest1;. The file name, use statement and package statement must* match.
Works fine with ($OK,$MSG) = (\&{$SUB."::Test_Ldev"})->($LDEVID); and does not need to modify all the functions in the package
I'm aware of that since I'm the one who told you that solution. But it's a pretty terrible solution compared to the one presented in this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.