jhanna has asked for the wisdom of the Perl Monks concerning the following question:

This is really simple, but I can't figure it out. It's just a presidence / syntax thing, but I can't find the right combo.

I'm trying to reference an object's method. The object is $o, the method is foo_edit. The trouble is foo is a value in $bar. $o->$bar."_edit"() fails. What's the correct ()'s and {}'s to make this work?

If i do my $b=$bar."_edit" and $o->$b() it works, but I don't wanna make temp vars like that.

{$o}->{$bar."_edit"}() fails (undefined &main::).
$o->{$bar."_edit"}() fails (undefined &main::).
$o->"${bar}_edit"() fails (syntax near ->"${c}_edit").

Who can enlighten me on this mystery?

Replies are listed 'Best First'.
Re: object ref syntax
by merlyn (Sage) on Feb 08, 2002 at 23:44 UTC
    If i do my $b=$bar."_edit" and $o->$b() it works, but I don't wanna make temp vars like that.
    But that's about the only way to do an indirect method call. You can horse around with UNIVERSAL::can to get at it a bit differently, but you're still gonna end up with either a temporary variable or a value in passing.

    Symbolic method calls are rare enough that it was deemed reasonable to restrict them to simple scalars.

    -- Randal L. Schwartz, Perl hacker

      *sigh* -- I'm spoiled by perl's TAAWTDI (there's always another way to do it) heritage.

        Just to elucidate on merlyn's can method (no pun intended), the following works just fine:

        $b = "foo"; $o->can($b . "_edit")->();

        bbfu
        Seasons don't fear The Reaper.
        Nor do the wind, the sun, and the rain.
        We can be like they are.

Re: object ref syntax
by Anonymous Monk on Feb 09, 2002 at 01:08 UTC
    Mystery unraveled!

    $o->${\"${bar}_edit"}();

    Cheers,
    -Anomo
      It's not that complex, nor is it a mistery.
      $o->${$bar.'_edit}()
      also, dude was trying "$bar._edit" which wasn't an existing method
Re: object ref syntax
by enoch (Chaplain) on Feb 09, 2002 at 17:14 UTC
    Wouldn't an eval work?
    eval("\$o->" . $bar . "_edit()");
    Jeremy