Running:
use strict;
use warnings;
my @list = ( "abc", "def" );
my $nelts = 3;
# Case 1
{
my @arr = ( [@list] ) x $nelts;
for my $e (@arr) { print "Case 1 before: $e: $e->[0] $e->[1]\n" }
$arr[0]->[0] = "xyz"; $arr[0]->[1] = "123";
for my $e (@arr) { print "Case 1 after : $e: $e->[0] $e->[1]\n" }
}
print "\n";
# Case 2
{
my @arr = map { [@list] } 1 .. $nelts;
for my $e (@arr) { print "Case 2 before: $e: $e->[0] $e->[1]\n" }
$arr[0]->[0] = "xyz"; $arr[0]->[1] = "123";
for my $e (@arr) { print "Case 2 after: $e: $e->[0] $e->[1]\n" }
}
produces:
Case 1 before: ARRAY(0x61ddc8): abc def
Case 1 before: ARRAY(0x61ddc8): abc def
Case 1 before: ARRAY(0x61ddc8): abc def
Case 1 after : ARRAY(0x61ddc8): xyz 123
Case 1 after : ARRAY(0x61ddc8): xyz 123
Case 1 after : ARRAY(0x61ddc8): xyz 123
Case 2 before: ARRAY(0x61de28): abc def
Case 2 before: ARRAY(0x315918): abc def
Case 2 before: ARRAY(0x315990): abc def
Case 2 after: ARRAY(0x61de28): xyz 123
Case 2 after: ARRAY(0x315918): abc def
Case 2 after: ARRAY(0x315990): abc def
As you can see, Case 1 above produces a list of identical references
(so that changing the value of the first item in the list results in all list values changing)
while with Case 2 above, changing the value of the first item leaves the
other list values unchanged.
Now Case 2 is the behavior I wanted but I (foolishly) started with:
my @arr = ( [@list] ) x $nelts;
... got surprised when changing one list element changed them all,
so randomly switched to:
my @arr = map { [@list] } 1 .. $nelts;
Since this is a fairly common operation, I was wondering
if there is a "standard" way to do Case 2.
How would you do it?