in reply to Calling arbitrary method from new

Are you looking for something like:

for my $argument ( keys %args ) { $self->$argument( $args{ $argument } ) if exists $hash{ '_' . $argument }; }

As a side note, I prefer to generate accessors at compile-time without using AUTOLOAD when possible. Unless you predeclare all of the methods you're generating with subs or provide your own can(), you've made life more difficult for users of your code.

Replies are listed 'Best First'.
Re^2: Calling arbitrary method from new
by mrborisguy (Hermit) on Jun 10, 2005 at 03:41 UTC

    Yes, I believe that is exactly what I want. I was trying to do something like $self->&{ $argument }( ... ), so I can't believe I didn't try this.

    On the other note: Is it really better to declare all of my methods, even if they are all so similar? I was reading through one of the intro to OO articles in the perldocs, which said AUTOLOAD is good, but I can see your point. Maybe I'll have to rewrite some of my code then.

    Thanks for the help!

        -Bryan

      No ampersand, but the way chromatic wrote it:

      $self->$argument( ... )
      Recently there was an interesting discussion on the use of AUTOLOAD for accessor generation; it starts here. In particular, tilly's first reply illustrates the approach that chromatic alluded to.

      the lowliest monk

      If I have a number of very similar methods, I like to highlight that by generating them in a loop with something like:

      for my $method (qw/ foo bar /) { no strict 'refs'; *$method = sub { use strict 'refs'; my $self = shift; $self->{"_$method"} = shift if @_; return $self->{"_$method"}; } }

      I'd usually use AUTOLOAD for this only if the list is infinite - for example if attribute methods are created on demand for arbitrary attributes supplied for the user.

      Hugo