Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic execution. Is there such a thing? 3

Status
Not open for further replies.

ejaggers

Programmer
Feb 26, 2005
148
US
Can you pass dynamically execute code in Perl. i.e.

chomp($subname = <STDIN>);
$y = $subname();
 
What he appears to want to do is use a hash where the subroutine name is the hash key and the value is a reference to code or a subroutine. He can then use the name of the subroutine as a reference to the subroutine.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Kevin,

Actually what I have is: sub1(),sub2()...sub20();

Is there a way to say:

chomp($x = <STDIN> );
sub$x();
 
Hi

As Kevin already mentioned, this :
Code:
sub sub1 { print "one\n" }

sub sub2 { print "two\n" }

sub sub3 { print "three\n" }

foreach $x (1..3) {
  print "running sub #$x :\n";
  &{"sub$x"};
}
will output this :
[tt]
running sub #1 :
one
running sub #2 :
two
running sub #3 :
three
[/tt]
Now go ahead and try it out.

Feherke.
 
Kevin,

please give an example of how to do it your way
I'm not that familiar with references
 
I tried your solution above, and went from 67 lines of code down to 26. That was awsome!!! Thanks again

And thanks for the link to references.
 
Using a hash example:


Code:
use strict;
use warnings;

my %coms = (
   foo => \&foo,
   bar => \&bar,
);

foreach my $x qw(foo bar) {
  print "running sub $x :\n";
  $coms{$x}->($x);
}

sub foo {
   my $arg = $_[0];
   print "in $arg sub\n";
}

sub bar {
   my $arg = $_[0];
   print "in $arg sub\n";
}


------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top