in reply to Re^3: Fields pragma - the poor man's OO framework?
in thread Fields pragma - the poor man's OO framework?
However if restriction to given values is wanted, I'd suggest Hash::Utils as it is core in 5.8 and above (and it does the restriction natively rather than using tie).
output:package Foo; use strict; use Hash::Util qw( lock_keys ); my @attrs = qw( name alias race ); sub new { my $class = shift; my %args = @_; my $self = bless {}, $class; lock_keys(%$self, @attrs); foreach my $k ( @attrs ) { if ( exists $args{$k} ) { $self->{$k} = $args{$k}; } } return $self; } package main; my $c = Foo->new(name => 'Aragorn', alias => 'Strider', race => 'Human +'); print "name: $c->{name}\n"; print "job: $c->{job}\n";
As it happens, fields in 5.10 is implemented using Hash::Utils' restriction mechanism.$ perl test.pl name: Aragorn Attempt to access disallowed key 'job' in a restricted hash at test.pl + line 26.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: Fields pragma - the poor man's OO framework?
by dragonchild (Archbishop) on Jul 07, 2008 at 12:58 UTC | |
by waba (Monk) on Jul 08, 2008 at 18:54 UTC |