in reply to Calling OO-method From A Hash

You said it yourself: $quiz->$act()

Replies are listed 'Best First'.
Re: Re: Calling OO-method From A Hash
by Fletch (Bishop) on Mar 03, 2004 at 02:58 UTC

    Of course the truly paranoid will make sure that it's a valid method first.

    my $method = $q->param( 'method' ); # ... or whatever if( my $m = $obj->can( $method ) ) { $obj->$m( @params ); } else { die "I can't call $method on a ", ref $obj; }
      beware of method names like "main::unsafe" for example. can() will return \&main::unsafe and not undef. this is also addressed in perlsec.pod.
      better will be checking in a dispatch table in case $method comes from outside.
      A reply falls below the community's threshold of quality. You may see it by logging in.

      And the knowledgable would know that the extra code doesn't get you much, since calling an invalid method will die as it is...

        The more knowledgeable would realize the die was just an example and that they could replace it with code which gracefully handles the problem (perhaps redirecting to an error page, or listing the valid methods).

Re: Re: Calling OO-method From A Hash
by dejoha (Novice) on Mar 03, 2004 at 05:12 UTC

    Thanks!

    This worked perfectly. I don't know what I was smoking! Maybe I just needed to tell someone else.

    Sorry to bother the Monks with such trivialities…

    www.dejoha.com … www.derekandmelissa.com
Re: Re: Calling OO-method From A Hash
by bart (Canon) on Mar 03, 2004 at 08:42 UTC
    I'd like to make a small note, namely despite being a symbolic reference (in my book),
    $quiz->$act()
    passes strict without any form of complaint.
    use strict; sub Foo::hello { shift; printf "Hello, %s!\n", shift; } my $meth = "hello"; my $class = "Foo"; $class->$meth("world");
      Method lookup is done at runtime. So, what's wrong with allowing an extra dereference?

      It does bring up the point that $class->$meth() is not the same as $meth($class). (It is, however, the same as $class->can($meth)->($class). *grins*)

      ------
      We are the carpenters and bricklayers of the Information Age.

      Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.