Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying arrays from one reference to another in perl

I have a reference to an anonymous array and I want to create a reference to a copy of that array. Here's how I do it:

my $ref1 = ['a','b','c',];
my @arr = @$ref1;
my $ref2 = \@arr;

now $ref2 points to a copy of the array. However, I don't actually care about @arr. Is there a way to perform such a copy without an intermediate variable?

Thanks.

like image 226
Yakov Dan Avatar asked Jan 25 '26 13:01

Yakov Dan


1 Answers

To create a reference to an array which is a copy of an array referenced by a variable $ref1, you can write:

my $ref2 = [@$ref1];

Now, $ref2 is the new reference.

like image 197
Håkon Hægland Avatar answered Jan 27 '26 06:01

Håkon Hægland



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!