Getting list of fields back from 'use fields' pragma?
- by makenai
So I'm familiar with the use fields pragma in Perl that can be used to restrict the fields that are stored in a class:
package Fruit;
use fields qw( color shape taste );
sub new {
my ( $class, $params ) = @_;
my $self = fields::new( $class ) unless ref $class;
foreach my $name ( keys %$params ) {
$self->{ $name } = $params->{ $name };
}
return $self;
}
My question is.. once I've declared the fields at the top, how I can get the list back.. say because I want to generate accessors dynamically? Is keys %FIELDS the only way?
Secondarily, is there a more efficient way to pre-populate the fields in the constructor than looping through and assigning each parameter as I am above?
Thanks!