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.
In reply to Re^4: Fields pragma - the poor man's OO framework?
by Arunbear
in thread Fields pragma - the poor man's OO framework?
by waba
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |