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?


In reply to Surprised by repetition (x) operator applied to a list by eyepopslikeamosquito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.