On Tue, Apr 12, 2011 at 10:30:06AM -0400, Shawn H Corey wrote:
> On 11-04-12 10:15 AM, marcos rebelo wrote:
> >On Tue, Apr 12, 2011 at 15:54, Paul Johnson<p...@pjcj.net>  wrote:
> >>>  On Tue, Apr 12, 2011 at 03:26:49PM +0200, marcos rebelo wrote:
> >>>>>  Hi all
> >>>>>
> >>>>>  I have a code like:
> >>>>>
> >>>>>  foreach my $key ( ... ) {
> >>>>>      my $sub = "get_$key";
> >>>>>      $self->$sub;
> >>>>>      ...
> >>>>>  }
> >>>>>
> >>>>>  If I can do this, I can also do it without the variable $sub.
> >>>
> >>>  You can do that.  You can also do it without the variable $sub.  But
> >>>  please don't.  It is much clearer with the variable in place.
> >>>
> >>>>>  What is the syntax? please
> >>>
> >>>    $self->${\"get_$key"};
> >>>
> >>>  But please pretend that the answer is "no, you need the variable $sub".
> >This one is so ugly
> >
> 
> What you're trying to do is called a symbolic reference.  It is not
> considered best practice.  Instead, use a hash:
> 
> my %sub_hash = (
>   foo => \&foo,
>   bar => \&bar,
> );
> 
> ...
> 
> foreach my $key ( ... ){
>   $sub_hash{$key};
> }
> 
> __END__
> 
> You also don't need $self since the subs are methods to the class
> and are in the same file.

I believe you are mistaken here.  The technique is fine, and $self is
necessary to call a method rather than a specific subroutine - consider
the case where there is a class hierachy and @ISA is searched.

Your solution would work well were we not dealing with OO.

Either that or I have misunderstood the original question.

-- 
Paul Johnson - p...@pjcj.net
http://www.pjcj.net

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to