1

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 ?

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

push @arr2D, [ split( /,/, $elem ) ]; would remove the need for $i
Hunter: Yes, if @arr2D were empty at the start. It wasn't clear to me if it was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.