Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create many hash references with identical data?

Tags:

perl

I am trying to create many hash references with identical contents. Using the x operator gives copies of the same reference. How can I get different references?

I need different references so that I can later update them independently of others.

My Code:

use strict;
use warnings;
use autodie;

use feature qw(say);
use open ':std', ':encoding(UTF-8)';

my %UNIT_COUNT = (
    numsys   => 6,
    alg      => 20,
    geo      => 15,
    cogeo    => 6,
    trig     => 12,
    mensur   => 10,
    statprob => 11
);

my $out = [
       map {
            ( { unit => $_, weight => 1 } ) x
              ( $UNIT_COUNT{$_} )
        } keys %UNIT_COUNT
    ];

use Data::Dumper;
print Dumper($out);
like image 454
pii_ke Avatar asked Mar 02 '23 17:03

pii_ke


1 Answers

This uses another map instead of the x operator, but it does give you copies:

my $out = [
    map {
        my $k = $_;
        map { { unit => $k, weight => 1 } } 1 .. $UNIT_COUNT{$_}
    } keys %UNIT_COUNT
];

Partial output:

$VAR1 = [
          {
            'unit' => 'mensur',
            'weight' => 1
          },
          {
            'weight' => 1,
            'unit' => 'mensur'
          },
          {
            'unit' => 'mensur',
            'weight' => 1
          },
          {
            'unit' => 'mensur',
            'weight' => 1
          },
like image 71
toolic Avatar answered Mar 12 '23 07:03

toolic