in reply to Dynamically calling different functions?

Here is the code with the module:
You can use different names of operation and subs here.
package Register; use strict; sub new { my $class = shift; my $self = {_register => 0 }; bless $self, $class; } sub set { my $self = shift; $self->{_register} = shift; } sub add { my $self = shift; $self->{_register} += shift; } sub multiply { my $self = shift; $self->{_register} *= shift; } sub value { my $self = shift; return $self->{_register}; } package main; my $r = new Register; my $ops = { set => 'set', add => 'add', mul => 'multiply', }; while(<DATA>){ s/^\s+//; s/\s+$//; my ($operation,$param) = split; my $sub = $ops->{$operation}; $r->$sub($param); print $r->value,"\n"; } __DATA__ set 5 add 2 mul 2

artist

Replies are listed 'Best First'.
Re: Re: Dynamically calling different functions?
by Anonymous Monk on Jun 30, 2003 at 20:22 UTC
    I confess, I had done some reading about all this stuff before... how does this relate to the "no strict 'refs';" stuff? I just tried out this code, and it appears as though you're getting around the:
    use strict; $name = "call_this_func"; &{$name}();

    ...restrictions (which I don't quite understand). Is it because you are calling a function of an object? Or is it because you are using the $a->() format? My perl-fu is weak, but I would appreciate some understanding. Thanks!

    --Robert

      Straight from the docs:

      strict subs' : This disables the poetry optimization, generating a compile-time error if you try to use a bareword identifier that's not a subroutine, unless it appears in curly braces or on the left hand side of the "=>" symbol.

      artist