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

I'm creating a perl object class and in the 'new' constructor I want to test the attributes submitted. I test for allowable keys and make sure there's a value for every key.

Is there a module for doing this kind of stuff? Something besides Moose...

This is how I do it now:
sub new { my ( $class, @attributes ) = @_; my $self = {@attributes}; # make sure we got valid argument keys if ( @attributes ) { my $key_hash = {@attributes}; my @keys = keys %$key_hash; my @invalid_attribute_key = grep { my $tested_attributes = $_; not grep { $tested_attributes eq $_ } qw(attribute_1 attribute_2 attribute_3); } @keys; croak "invalid attribute key(s) in constructor: @invalid_attri +bute_key" if @invalid_attribute_key; } bless $self, $class; return $self; }

Replies are listed 'Best First'.
Re: Module to Check Constructors?
by moritz (Cardinal) on Mar 09, 2012 at 17:04 UTC

    There are various OO modules that try to provide some of the convenience that Moose provides, while reducing the cost. For example Moo, Mo and M. Maybe one of them does what you want. Or search for terms like object and class.

    That said your use of strict validation and construction in the same method makes it very hard to subclass from your classes. If that's not what you want, you might consider splitting up the two, and maybe provide an initialization methods that subclasses can call on an already blessed hash.

      M is just a joke module. Mouse (and its friend Any::Moose) might be of more practical use.

        M is just a joke module.
        Moo and Mo are not. What is Perl without jokes, anyway?
Re: Module to Check Constructors?
by Arunbear (Prior) on Mar 09, 2012 at 17:59 UTC
    Yes, see e.g. Params::Validate
    update
    An example:
    #!/usr/bin/perl use strict; use warnings; use v5.10; package Player; use Params::Validate qw(:all); sub new { my $class = shift; my %attr = validate(@_, {name => 1, race => 1}); return bless \%attr => $class; } package main; my $player = Player->new(race => 'Elf', name => 'Legolas'); # dies: missing attribute my $player2 = Player->new(race => 'Dwarf'); # dies: unknown attribute my $player3 = Player->new(race => 'Hobbit', name => 'Bilbo Baggins', s +ize => 'small'); say 'done';
Re: Module to Check Constructors?
by JavaFan (Canon) on Mar 09, 2012 at 17:46 UTC
    Untested:
    package Whatever; my @required = qw[key1 key2 key3]; sub new { bless {}, shift; } sub init { my $self = shift; my %attr = @_; foreach my $required (@required) { die "Required attribute $required missing" unless exists $attr{$required}; } @$self{keys %attr} = values %attr; $self; } my $obj = Whatever::->new->init(key1=>1, key2=>2, key3=>3);