in reply to Referencing methods

Unfortunately you can't create a reference to an object method due to the fact that calling an object method is really just dereferencing the object with some blessed magic. One approach would be to use an anonymous sub e.g
iterate(sub { $rep->attach(@_) }, @param);
But as is suggested in the nodes above, it'll probably be better to refactor your sub.
HTH

_________
broquaint

update: doh! as chip points out, it helps if you pass the parameters

Replies are listed 'Best First'.
Re: Re: Referencing methods
by Elian (Parson) on May 08, 2003 at 15:55 UTC
    Unfortunately you can't create a reference an object method
    Luckily this turns out not to be the case. can returns a reference to the method you're looking for, and undef if that method doesn't exist, so you can write code like:
    my $ref = $obj->can($meth_name); $ref->($obj, @params);
    if that floats your boat. Just remember that what's returned is a regular sub ref, so you need to pass in the object or class name as the first parameter.
      Luckily this turns out not to be the case. can returns a reference to the method you're looking for
      True ... kinda. It returns a reference to a class method to the appropriate sub, I know this is just playing with semantics, but when I call an object method I expect the caller to passed in to the method (well, in the world of perl at least). If you really wanted can to return an object method reference (or at least my expectation of one :) in that situation then you could use some code I whipped up for diotalevi's Why isn't ->can() curried?.

      Update: Elian rightly points out there isn't any difference between class and object methods, which I knew, but didn't write correctly in the node ('class method' ne 'sub in appropriate package'). Basically my point was that can returns a sub reference not a 'method' reference i.e you call it, and it implicitly makes the caller as the first arg in the arg list.
      HTH

      _________
      broquaint

        There isn't any difference between a class and object method, not in perl. Or subs, for that matter. They're all just subs. Making a method call just takes what's on the left of the arrow and sticks it in the arg list as the first argument--it's how you call, not what you call, that makes the difference.

        Whether this is good or not is a separate question. I merely note on how it is, not how good it is. The current scheme is perfectly adequate for what the OP was looking for.