我怎样才能通过嵌套数组迭代? [英] How can I iterate through nested arrays?

查看:121
本文介绍了我怎样才能通过嵌套数组迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个数组如下:

I have created an array as follows

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

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

每行有两个数字。

each line has two numbers.

15 6
2  8

如何在每行中的每个项目迭代?

how do iterate over each item in each line?

即。我想打印

15
6
2
8

我知道这是类似

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

    print "?????
}

这是我在哪里卡住了。

推荐答案

查看 perldsc 文档。这就是Perl数据结构食谱,其中有处理数组的数组的例子。从你在做什么,虽然,它看起来并不像你需要一个数组的数组。

See the perldsc documentation. That's the Perl Data Structures Cookbook, which has examples for dealing with arrays of arrays. From what you're doing though, it doesn't look like you need an array of arrays.

有关您服用两个数字每行输出,每行一个号码,只需打开空白变成换行符问题:

For your problem of taking two numbers per line and outputting one number per line, just turn the whitespace into newlines:

 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一行程序,这只是:

As a Perl one-liner, that's just:

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

这篇关于我怎样才能通过嵌套数组迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆