PYPL
PYPL

Reputation: 1849

How to create two dimensional array with 2 arrays

How to create multiple dimentional array with 2 arrays?

      @param=("param1","param2","param3");
      @value=("value1_1, value1_2, value1_3", "value2_1, value2_2, value2_3","value3_1, value3_2, value3_3");

      Output:
      @out=(["param1"]["value1_1", "value1_2", "value1_3"], ["param2"]["value2_1", "value2_2", "value2_3"], ["param3"]["value3_1", "value3_2", "value3_3"])

I've tried this way:

      $j=0;
      foreach $i(@param1){
                push @{$out[$i]}, split(", ", $value[$j]);
                $j++;}

Upvotes: 0

Views: 91

Answers (1)

amon
amon

Reputation: 57600

It's not exactly clear to me what data structure you want to create. However, I assume you are trying to create a hash of arrays (a hash table is also known as dictionary or associative array), not an array. The difference in Perl is that an array always uses integers as keys, whereas a hash always uses strings.

The resulting data structure would then look like

%out = (
  'param1' => ['value1_1', 'value1_2', 'value1_3'],
  'param2' => ['value2_1', 'value2_2', 'value2_3'],
  'param3' => ['value3_1', 'value3_2', 'value3_3'],
);

We can create this data structure like so:

my %out;
for my $i (0 .. $#param) {
  $out{$param[$i]} = [split /,\s*/, $value[$i]];
}

Note that $#foo is the highest index in the @foo array. Therefore, 0 .. $#foo would be the range of all indices in @foo. Also note that entries in hashes are accessed with a curly brace subscript $hash{$key}, unlike arrays which use square brackets $array[$index].

You can access multiple elements in a hash or array at the same time by using a slice@foo{'a', 'b', 'c'} is equivalent to ($foo{a}, $foo{b}, $foo{c}). We can also transform a list of elements by using the map {BLOCK} LIST function. Together, this allows for the following solution:

my %out;
@out{@param} = map { [split /,\s*/, $_] } @value;

Inside the map block, the $_ variable is set to each item in the input list in turn.

To learn more about complex data structures, read (in this order):

You can also read the documentation for the map function and for the foreach loop.

Upvotes: 4

Related Questions