How can I assign many Moose attributes at the same time?
attributes, moose, perl
Solution
Pass the attributes to the constructor using `zip` from the `List::MoreUtils` module:
use List::MoreUtils qw/ zip /;
my $object = My::Record->new(
zip @field_names,
@{[ split /\|/, get_line_from_file ]}
);
Problem
I'm gradually Moose-ifying some code that reads lines from a pipe delimited, splits each and assigns adds them to a hash using a hash slice. I've turned the hash into a Moose class but now I have no idea how to quickly assign the fields from the file to the attributes of the class (if at all). I know I can quite easily just do: ``` my $line = get_line_from_file; my @fields = split /\|/, $line; my $record = My::Record->new; $record->attr1($fields[0]); ... ``` but I was hoping for a quick one liner to assign all the attributes in one go, somewhat akin to: ``` my $line = get_line_from_file; my %records; @records{@field_names} = split /\|/, $line; ``` I've read about coercion but from what I can tell it's not what I'm after. Is it possible? Thanks