Search code examples
arraysperljoinmultidimensional-arrayperl-data-structures

How do I access arrays of array in perl?


Hi I have a array as myarray. I would like to make a list as '1 2 3' which is joining the first subarray. My string is printing the memory location I suppose instead of list. any help will be appreciated.

@myarray = [[1,2,3],[4,5,6],[7,8,9]];
for (my $i=0; $i < @myarray; $i++) {
my @firstarray = $myarray[$i];
my $mystring = join("", @firstarray);
print "My string ".$mystring . ". "\n";
}

Solution

  • You have to dereference the inner array reference by @{ ... }. Also, do not use [...] for the top structure - use normal parentheses (square brackets create an array reference, not an array). There was also a problem with the concatenation on your print line:

    @myarray = ( [1,2,3], [4,5,6], [7,8,9] );
    for (my $i=0; $i < @myarray; $i++) {
        my @firstarray = @{ $myarray[$i] };
        my $mystring = join("", @firstarray);
        print "My string " . $mystring . ".\n";
    }