On Nov 12, 2005, at 2:56 AM, James Reynolds wrote:

Is there someway to execute this code like this:

$subroutine_name = "something"; # can't change
$hashref->{'key'}='value'; # can't change

eval "$subroutine_name($hashref)"; # how do I eval this? It doesn't eval.

Essentially I get the subroutine names to execute from a text file, and there will be thousands of differently named subroutines. I simplified the reason why the hash exists in this example. Needless to say I can't get out of using it that way easily, if at all.

Block eval() is useful for exception handling, but string eval() is just evil misspelled.

Use a dispatch table instead:

    #!/usr/bin/perl

    use strict;
    use warnings;

    my %dispatch = (
        'a' => \&a,
        'b' => \&b,
        'c' => \&c,
    );

    my $hashref = {
        'foo' => 1,
        'bar' => 2,
        'baz' => 3,
    };

    for my $sub_name ('a', 'b', 'c') {
        $dispatch{$sub_name}->($hashref);
    }

    sub a {
        my ($hr) = @_;
        print "A called\n";
        print "\t", join(",", keys(%$hr)), "\n";
    }

    sub b {
        my ($hr) = @_;
        print "B called\n";
        print "\t", join(",", keys(%$hr)), "\n";
    }

    sub c {
        my ($hr) = @_;
        print "C called\n";
        print "\t", join(",", keys(%$hr)), "\n";
    }

Have a look in the archives for comp.lang.perl.misc at Google Groups - the subject of "dispatch tables" has been covered at great length:

http://groups.google.com/group/comp.lang.perl.misc/search? group=comp.lang.perl.misc&q=dispatch+table

sherm--

Cocoa programming in Perl: http://camelbones.sourceforge.net
Hire me! My resume: http://www.dot-app.org

Reply via email to