How can I iterate through nested arrays?

后端 未结 5 715
独厮守ぢ
独厮守ぢ 2021-01-22 03:59

I have created an array as follows

while (defined ($line = ``))

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


        
5条回答
  •  梦谈多话
    2021-01-22 04:18

    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
         }
    

    With Perl 5.10, you can use the new \h character class that matches only horizontal whitespace:

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

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

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

提交回复
热议问题