NetWallah has asked for the wisdom of the Perl Monks concerning the following question:

Using the "x" operator in a list context generates a list that seems to be optimized at assignment such that the first element is properly generated, and subsequent elements are simply references to the first.

use Data::Dumper; my @x; push @x, ({a=>3,b=>4}) x 5 ; $x[3]->{b}=9; # I want to modify the Fourth element only print Dumper ( \@x);" -- Output -- $VAR1 = [ { 'a' => 3, 'b' => 9 }, $VAR1->[0], $VAR1->[0], $VAR1->[0], $VAR1->[0] ];
As you can see, it does NOT do what I want - it modifies ALL elements (since they are references), not just a single one.

I have, in the past, got around this using map to generate individual elements, but, at this point, I am irritated that "x" will not comply, and I am seeking monk wisdom in subjugating it. At the very minimum, I'd like to understand the behaviour or history related to this implementation of the operator.

I have previously referred to this issue in a response to this node, with a fellow monk agreeing that it was an enigma, but no solution.

Probably irrelevant info: perl, v5.8.7 built for MSWin32-x86-multi-thread.

Update:Thanks merlyn. I guess that means that "x", by design/definition is not suited/usable for this purpose. Veni, Vedi, Vici is a fantasy. Sigh!.

     "For every complex problem, there is a simple answer ... and it is wrong." --H.L. Mencken

Replies are listed 'Best First'.
Re: Conquering "x" operator over-optimization
by merlyn (Sage) on Feb 26, 2006 at 18:32 UTC
    No, it's doing what you told it to do. You've taken a hashref, and made 5 copies of the reference with "x". What you probably wanted was a deep copy, not a shallow copy.

    However, for this example, you can cheat with a map instead of an "x":

    my @x = map +{a => 3, b => 4}, 1..5;

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.