A few nodes dealing with attribute issues over the last little while prompted me to learn a little about this rather under used feature of Perl. A need to validate parameter lists to object constructors and option setting members inspired me to rope attributes into the task. Consider:

package Entity; use strict; use warnings; my %okParams; my %paramBase; sub FETCH_CODE_ATTRIBUTES { my ($package, $referrent) = @_; return () unless exists $paramBase{$package}; return @{$paramBase{$package}}[1 .. $#{$paramBase{$package}}]; } sub MODIFY_CODE_ATTRIBUTES { my ($package, $referrent, @attrs) = @_; @attrs = map {"-$_"} @attrs; $okParams{$_} = $package for @attrs; $paramBase{$package} = \@attrs; return (); } sub new: Id { my ($class, %params) = @_; my %self; @self{keys %okParams} = @params{keys %okParams}; my @badParams = grep {! exists $self{$_}} keys %params; warn "Class $class doesn't accept the following parameters: @badPa +rams" if @badParams; return bless \%self, $class; } 1; package Member; use base qw(Entity); sub new: Name Nick Age Gender { my ($class, %params) = @_; return Entity::new ($class, %params); } 1; package main; my $member = Member->new (-Name => 'fred', -Id => 1, -Wibble => 1);

generates the warning:

Class Member doesn't accept the following parameters: -Wibble at nonam +e.pl line 42.

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re: Attributes with new to manage parameters
by dragonchild (Archbishop) on Sep 15, 2007 at 03:10 UTC
    Instead of using a ton of attributes, why not do something like
    sub new : Attrs( 'name', 'nick', 'age', 'gender' ) { .... }
    That way, the other attributes aren't clobbering potential other uses, like what Catalyst does.

    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?

      That (and more, like providing validation information) occurred to me after posting the node. However the elegance of the original code seems to me to be just fine for a "simplest case" and can be embroidered to suit as circumstances require.


      DWIM is Perl's answer to Gödel