How can I assign many Moose attributes at once?

I am gradually trying to use code that reads lines from a delimited pipe, breaks each one and assigns it to the hash using a hash fragment.

I turned the hash into a Moose class, but now I have no idea how to quickly assign fields from a file to class attributes (if at all).

I know that I just can simply do:

my $line = get_line_from_file; my @fields = split /\|/, $line; my $record = My::Record->new; $record->attr1($fields[0]); ... 

but I was hoping that a fast one liner would assign all the attributes at once, somewhat akin to:

 my $line = get_line_from_file; my %records; @records{@field_names} = split /\|/, $line; 

I read about coercion, but from what I can say, not what I need.

Is it possible?

thanks

+6
perl attributes moose
source share
3 answers

Pass attributes to the constructor using zip from the List::MoreUtils :

 use List::MoreUtils qw/ zip /; my $object = My::Record->new( zip @field_names, @{[ split /\|/, get_line_from_file ]} ); 
+11
source share

I think you're on the right track with a hash segment approach. I would do something like:

 my %fields; @fields{@field_names} = split m{\|}, $line; my $record = My::Record->new( %fields ); 

You might be able to come up with a gnarly map solution to achieve the same, but I would be wrong on the readability side here.

+7
source share

If the object is not yet constructed, you can simply pass all the keys and values โ€‹โ€‹to the constructor:

 my $line = get_line_from_file; my %records; @records{@field_names} = split /\|/, $line; my $object = My::Record->new(%records); 

or if the object has already been created and you want to add several new fields:

 my $line = get_line_from_file; my %records; @records{@field_names} = split /\|/, $line; while (my ($key, $value) = each(%records) { $object->$key($value); # or if you use different names for the setters than the "default": $object->set_value($key, $value); } 
+3
source share

All Articles