in reply to Best way to initialize hash x repetition array?

The repeated expression is only evaluated once, so you are reusing the same anonymous array for each element of the hash. You can map instead of the repetition operator if you want the expression to be evaluated for each repetition.

For example, the problem can be solved by replacing

my %hash3; @hash3{keys(%hash3_origin)} = ([0, 0]) x keys(%hash3_origin);
with
my %hash3; @hash3{keys(%hash3_origin)} = map { [0, 0] } 1..keys(%hash3_origin);

That said, the following are much simpler:

my %hash3; $hash3{$_} = [0, 0] for keys(%hash3_origin);
or
my @hash3 = map { $_ => [0, 0] } keys(%hash3_origin);

Replies are listed 'Best First'.
Re^2: Best way to initialize hash x repetition array?
by Veltro (Hermit) on Jun 29, 2018 at 21:49 UTC

    Ah, thanks for that and of course! I was so focused on getting this x operation to work that I completely lost attention to other useful constructs. I really like the one with 'for'. I avoid using map where I can (personal preference)

    The x operator is too bad though. The repeat operator x does repeat the array reference because as you said: The repeated expression is only evaluated once. But (0) in (0) x ... is also evaluated once, but still we get a copy of 0 for each assignment and we can get a reference to 0 for every assignment if we want too. So why can't the language detect when it is dealing with an array instead of an array reference and return a copy of eachthe 'evaluated' array expression for us too...

    The last thing that I'd like to find now is something that automatically generates [0, 0] or [0, 0, 0 ...]. It would be easy to forget to change the size of the initialization list in code after changing the size of the arrays in the hash.

      The last thing that I'd like to find now is something that automatically generates 0, 0 or 0, 0, 0 ....

      [0]{} Perl> print [ (0) x $_ ] for 1 .. 4;; ARRAY(0x36fed28) ARRAY(0x36fecf8) ARRAY(0x36fece0) ARRAY(0x36fecc8) [0]{} Perl> print @{ [ (0) x $_ ] } for 1 .. 4;; 0 0 0 0 0 0 0 0 0 0

      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority". The enemy of (IT) success is complexity.
      In the absence of evidence, opinion is indistinguishable from prejudice. Suck that fhit

        Yes, I already had something like that in my original solution.

        But what I meant was determining the max size to use:

        my $h3_columns = 2 ; # use List::Util qw(max) ; max (each array size) += 2 $hash3{$_} = [ (0) x $h3_columns ] for @keys3_origin ;

        I will find a solution for that, no worries. But that will be after this weekend.