eyepopslikeamosquito has asked for the wisdom of the Perl Monks concerning the following question:
Running:
produces: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" } }
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: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
... got surprised when changing one list element changed them all, so randomly switched to:my @arr = ( [@list] ) x $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?my @arr = map { [@list] } 1 .. $nelts;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Surprised by repetition (x) operator applied to a list
by BrowserUk (Patriarch) on Mar 30, 2014 at 03:29 UTC | |
by Athanasius (Archbishop) on Mar 30, 2014 at 03:55 UTC | |
|
Re: Surprised by repetition (x) operator applied to a list
by Anonymous Monk on Mar 30, 2014 at 02:42 UTC |