Thread

Posted on Wed Jan 4 23:30:12 2006 by arguile
Passing 'straight' arguements to a constructor.

While for more advanced object initialization the whole InitArgs method is great, for some object construction I'd prefer access to @_ as passed to new. Especially when recreating existing APIs.

I've been looking through the documentation and source code and can't seem to find a simple way to do it. All any init method gives me is a hasref. Coercing (kludging) it back into an array doesn't work as uneven parameters yields an exception and references are stringified if they occupy a hash key location.

# Example my $foo = Some::Thing->new(4,5,6); package Some::Thing; { sub _init :Init { my ($self, @args) = @_; # $args->[1] == 5 at this point. } }

Am I just missing something? Idea?

Direct Responses: 1589 | Write a response
Posted on Fri Jan 6 15:42:47 2006 by jdhedden in response to 1572
Re: Passing 'straight' arguements to a constructor.
    ... for some object construction I'd prefer access to @_ as passed to new. Especially when recreating existing APIs.

The cons of passing non-parameterized arguments in an object constructor are discussed in Perl Best Practices, and Object::InsideOut was written to follow most of Damian Conway's suggestions (with the additional flexibility of not putting everything into a hash ref).

However, to workaround the requirement for parameterized arguments, you can just put a wrapper around Object::InsideOut's new() method as follows:
#!/usr/bin/perl use strict; use warnings; package My::Class; { use Object::InsideOut; my %init_args :InitArgs = ( 'args' => '' ); sub init :Init { my ($self, $args) = @_; my @args = @{$args->{'args'}}; # Here's your non-parameterized args! print ('Args: ', join(', ', @args), "\n"); } # A wrapper around Object::InsideOut's ->new() method sub new { my $thing = shift; return ($thing->Object::InsideOut::new('args' => [ @_ ])); } } package main; MAIN: { my $obj = My::Class->new(1, 3, 9); } exit(0);
Direct Responses: 1594 | Write a response
Posted on Fri Jan 6 20:33:00 2006 by arguile in response to 1589
Re: Passing 'straight' arguements to a constructor.

Yes, I've read the book. Existing entrenched APIs are – unfortunately – just that; entrenched. And for four arguements or less I simply don't always agree with the book :).

Though I must be rather obtuse as I tried supplying new() instead of inheritting it, but didn't even think to just wrap the args.

Thanks!
Write a response