in reply to Syntax question: Method call, where method name is calculated from an expression

use strict; use warnings; use 5.010; sub f { 'g' } sub g { say 'in g()' }; (bless {})->can(f())->();
  • Comment on Re: Syntax question: Method call, where method name is calculated from an expression
  • Download Code

Replies are listed 'Best First'.
Re^2: Syntax question: Method call, where method name is calculated from an expression
by rovf (Priest) on Dec 04, 2009 at 15:48 UTC

    Looks great, but this doesn't work if the method expects parameters. For instance:

    package Obj; sub new { my $class=shift; my $self={ x => 'uh' }; bless $self, $class; } sub howl { my ($self,$arg)=@_; print($self->{x}," $arg\n"); } package main; sub mname { 'howl' } my $x=Obj->new(); $x->howl('oh'); $x->can(mname)->('ah');
    The reason is that can() returns only a reference to the method, but the object ($x) is lost on the way. A workaround would be
    $x->can(mname)->($x,'ah');
    but this is ugly, since it requires us to mention the object twice.

    -- 
    Ronald Fischer <ynnor@mm.st>