我创建了一个数组如下

while (defined ($line = `<STDIN>`))

        {
        chomp ($line);
        push @stack,($line);
        }


每行有两个数字。

15 6
2  8


如何遍历每一行中的每个项目?

即我要打印

15
6
2
8


我了解这就像

foreach (@{stack}) (@stack){

    print "?????
}


这就是我被困住的地方。

最佳答案

请参见perldsc文档。那就是《 Perl数据结构食谱》,其中包含处理数组数组的示例。从您所做的事情来看,似乎并不需要数组。

对于每行取两个数字并每行输出一个数字的问题,只需将空格变成换行符即可:

 while( <> ) {
     s/\s+/\n/; # turn all whitespace runs into newlines
     print;     # it's ready to print
     }


在Perl 5.10中,可以使用仅与水平空白匹配的新\h字符类:

 while( <> ) {
     s/\h+/\n/; # turn all horizontal whitespace runs into newlines
     print;     # it's ready to print
     }


作为Perl的单行代码,这仅仅是:

 % perl -pe 's/\h+/\n/' file.txt

关于perl - 如何遍历嵌套数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1571501/

10-10 21:32
查看更多