AWRAM
AWRAM

Reputation: 333

perl split the element of array into another 2D array error

I have an array that contains strings looking like this s1,s2,.. I need to split on "," and have the strings in another 2D array that's my code

 @arr2D;
     $i=0;
     foreach $a (@array){
    $arr2D[$i]= split (/,/,$a);
    $i++;
     }
//print arr2D content 
    for ($j=0;$j<scalar @arr;$j++){
    print $arr2D[$j][0].$arr2D[$j][1]."\n";
    }

the problem is while trying to print arr2D content I got nothing... any suggestion ?

Upvotes: 1

Views: 701

Answers (1)

Joe Z
Joe Z

Reputation: 17956

You need to capture the result of the split into an array itself. Notice the additional brackets below. This captures the result into an array and assigns the array reference to $arr2D[$i], thus giving you the 2-D array you desire.

foreach my $elem (@array)
{
    $arr2D[$i] = [ split( /,/, $elem ) ];
    $i++;
}

Also, you probably want to avoid using $a, since perl treats it specially in too many contexts. Notice I changed its name to $elem above.

Stylistically, you can eliminate the $i and the loop by rewriting this as a map:

@arr2D = map { [ split /,/ ] } @array;

That should work, and it's far more concise.

Upvotes: 4

Related Questions