Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create objects out of each element in array?

I have a module with a new constructor:

package myClass;

sub new
{
    my $class = shift;
    my $arrayreference = shift;
    bless $arrayreference, $class;
    return $arrayreference;
};

I want to do something like:

foreach $ref (@arrayref)
{
     $array1 = myClass->new($ref);
}

$array1 is being rewritten each time, but I want each element in the array to have a distinct object name (ex. $array1, $array2, $array3 etc.)

like image 627
user1224478 Avatar asked Feb 20 '26 22:02

user1224478


1 Answers

If you are working with a plural data structure (an array), then you need to store the result into a plural container (or multiple scalar containers). The idomatic way to do this is to use the map function:

my @object_array = map {myClass->new($_)} @source_array;

If you know that @source_array contains a fixed number of items, and you want scalars for each object:

my ($foo, $bar, $baz) = map {myClass->new($_)} @source_with_3_items;
like image 195
Eric Strom Avatar answered Feb 22 '26 15:02

Eric Strom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!