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

Could someone please help me to correct this syntax:

# This array of hashes keeps track of all test results my @tests = ( { name => 'Ping Test', subname => \&pingtest, result => 'Not performed' }, { name => 'Remdial', subname => \&remdial, result => 'Not performed' } ); # Loop through array of hashes and perform each test subroutine. foreach $x (@tests){ # Call subroutine. # What is the correct way to state this? # Without the references I would normally state # $result = testsub(); $x->{'result'} = $x->{'subname'}->(); print $x->{'result'}."\n"; # Stop testing if there is a failure. if ($x->{'result'} =~ m/Fail/) { last; } }

Neil Watson
watson-wilson.ca

Replies are listed 'Best First'.
Re: Syntax to call a subroutine from a reference
by chester (Hermit) on Sep 21, 2005 at 18:14 UTC
    Your version works fine for me, unless I'm missing something?

    # This array of hashes keeps track of all test results my @tests = ( { name => 'Ping Test', subname => \&pingtest, result => 'Not performed' }, { name => 'Remdial', subname => \&remdial, result => 'Not performed' } ); # Loop through array of hashes and perform each test subroutine. foreach $x (@tests){ # Call subroutine. # What is the correct way to state this? # Without the references I would normally state # $result = testsub(); $x->{'result'} = $x->{'subname'}->(); print $x->{'result'}."\n"; # Stop testing if there is a failure. if ($x->{'result'} =~ m/Fail/) { last; } } sub pingtest {print "ping\n"; return 123} sub remdial {print "dial\n"; return 456}

    Output:

    ping 123 dial 456
Re: Syntax to call a subroutine from a reference
by davidrw (Prior) on Sep 21, 2005 at 18:08 UTC
    you almost had it:
    $x->{'result'} = &{$x->{'subname'}}();
    Update: See perlref, especially example 2 in the "Using References" section.

    Update: As herveus notes, your original way of $x->{'result'} = $x->{'subname'}->(); does work as well...
      Howdy!

      $x->{subname}->() (as seen in the original code) also works fine. In fact, I would tend to prefer that over using the ampersand sigil.

      yours,
      Michael
Re: Syntax to call a subroutine from a reference
by herveus (Prior) on Sep 21, 2005 at 18:13 UTC
    Howdy!

    Your code looks fine...did you try it?

    yours,
    Michael
Re: Syntax to call a subroutine from a reference
by sh1tn (Priest) on Sep 21, 2005 at 18:10 UTC
    You have to define the given subroutines:
    # Your code here ... sub pingtest { print "I'm pingtest sub\n" } sub remdial { print "I'm remdial sub\n" }
    You may want to see perlsub.


Re: Syntax to call a subroutine from a reference
by neilwatson (Priest) on Sep 21, 2005 at 18:26 UTC
    You are correct. The syntax was right. My subroutine was the problem. Sorry to have bothered you all.

    Neil Watson
    watson-wilson.ca