perl将数组元素拆分为另一个2D数组错误

时间:2022-08-27 07:47:33

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

我有一个数组,其中包含类似于s1,s2,...的字符串。我需要拆分“,”并将字符串放在另一个2D数组中,这是我的代码

 @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 ?

问题是在尝试打印arr2D内容时我没有得到任何建议?

1 个解决方案

#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.

您需要将拆分的结果捕获到数组本身。请注意下面的附加括号。这会将结果捕获到一个数组中,并将数组引用赋给$ arr2D [$ i],从而为您提供所需的二维数组。

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.

此外,您可能希望避免使用$ a,因为perl会在太多的上下文中特别对待它。请注意,我将其名称更改为$ elem以上。

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

从风格上讲,你可以通过将其重写为地图来消除$ i和循环:

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

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

这应该有效,而且更加简洁。

#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.

您需要将拆分的结果捕获到数组本身。请注意下面的附加括号。这会将结果捕获到一个数组中,并将数组引用赋给$ arr2D [$ i],从而为您提供所需的二维数组。

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.

此外,您可能希望避免使用$ a,因为perl会在太多的上下文中特别对待它。请注意,我将其名称更改为$ elem以上。

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

从风格上讲,你可以通过将其重写为地图来消除$ i和循环:

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

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

这应该有效,而且更加简洁。