NateTut has asked for the wisdom of the Perl Monks concerning the following question:

What am I doing wrong here?
#!/usr/bin/perl use strict; use warnings; sub Procedure_Name_1 { my($Parm) = shift; print($Parm); } my %Procedures; $Procedures{'ProcName1'} = \&Procedure_Name_1; my $Procedure = 'ProcName1'; my $Parameter = 'Some Value'; &$Procedures->{$Procedure}($Parameter);
Update: Added -> to ref and fixed typo in title Update 2: To Clarify what I'm trying to do here is to call the sub reference stored in the Procedures hash with the argument $Parameter. This is a simplified case of my real world problem

Replies are listed 'Best First'.
Re: How to call a sub ref from a hash
by almut (Canon) on Dec 15, 2008 at 22:51 UTC

    If the syntax the other monks have pointed out is too confusing, you could also always use an intermediate variable:

    my $coderef = $Procedures{$Procedure}; $coderef->($Parameter);

    ...with the added benefit that even the average newbie would figure out the intention, just going by the variable name.

Re: How to call a sub reff from a hash
by Joost (Canon) on Dec 15, 2008 at 21:59 UTC
      I think you've goten me on the right track, but this:
      #!/usr/bin/perl use strict; use warnings; sub Procedure_Name_1 { my($Parm) = shift; print($Parm); } my %Procedures; $Procedures{'ProcName1'} = \&Procedure_Name_1; my $Procedure = 'ProcName1'; my $Parameter = 'Some Value'; &$Procedures->{$Procedure}($Parameter);
      still fails...

        Because you have no scalar $Procedures declared (you have a hash %Procedures, but that's something completely different).

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.

        Taking your code and then switching the last line like he said makes it work perfectly.

        #!/usr/bin/perl use strict; use warnings; sub Procedure_Name_1 { my($Parm) = shift; print($Parm); } my %Procedures; $Procedures{'ProcName1'} = \&Procedure_Name_1; my $Procedure = 'ProcName1'; my $Parameter = 'Some Value'; $Procedures{$Procedure}->($Parameter);

        I don't understand why you ignored his advice but i would recommend trying it as written in the future.

        BTW you could read the last line as "get the value of $Procedures{$Procedure} and then run it as a coderef ->( passing it $Parameter)"


        ___________
        Eric Hodges