Getting list of fields back from 'use fields' pragma?

Posted by makenai on Stack Overflow See other posts from Stack Overflow or by makenai
Published on 2010-03-31T03:49:16Z Indexed on 2010/03/31 3:53 UTC
Read the original article Hit count: 206

Filed under:

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!

© Stack Overflow or respective owner

Related posts about perl