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

Dear Monks

I have a question regarding Spiffy: How do I define the constructor to take parameters?

At the moment I provide the possibility to configure an object via an init method which the client should call right after constructing the object, however, I'd prefer to allow those parameters to be passed via new.

package VesrRec; use strict; use warnings; use Spiffy -Base; field 'raw'; sub new() { my $self = super; } sub init { my ($raw) = @_; $self->raw($raw); }
Thank you
Bernhard

Replies are listed 'Best First'.
Re: Spiffy: How to define the constructor to take parameters
by GrandFather (Saint) on Oct 28, 2007 at 19:48 UTC

    The following seems to be what you want:

    package VesrRec; use strict; use warnings; use Spiffy -Base; field 'raw'; sub new() { my ($class, $raw) = @_; my $self = bless {}, $class; $self->raw($raw); return $self; } package main; my $rec = VesrRec->new ('This one'); print $rec->raw ();

    Prints:

    This one

    Perl is environmentally friendly - it saves trees
      Thank you, Grandfather!

      This solution works nicely.

      Is there a way to use your solution but employing the "spiffy" call to $self->super instead of my $self = bless {}, $class; ?

      This would enable to fill in another superclass in the future without having to adapt the constructor.

      Thank you
      Bernhard

        Did you try just my $self = super; instead of reflexively posting a question?

        My criteria for good software:
        1. Does it work?
        2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?