How can I iterate through nested arrays?

后端 未结 5 702
独厮守ぢ
独厮守ぢ 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:19

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    while ( my $data =  ) {
        my @values = split ' ', $data;
        print $_, "\n" for @values;
    }
    
    
    __DATA__
    15 6
    2  8
    

    Output:

    C:\Temp> h
    15
    6
    2
    8
    

    Alternatively, if you want to store each line in @stack and print out later:

    my @stack = map { [ split ] } grep { chomp; length } ;
    

    The line above slurps everything coming from the DATA filehandle into a list of lines (because happens in list context). The grep chomps each line and filters by length after chomping (to avoid getting any trailing empty lines in the data file -- you can avoid it if there are none). The map then splits each line along spaces, and then creates an anonymous array reference for each line. Finally, such array references are stored in each element of @stack. You might want to use Data::Dumper to look at @stack to understand what's going on.

    print join("\n", @$_), "\n" for @stack;
    

    Now, we look over each entry in stack, dereferencing each array in turn, then joining the elements of each array with newlines to print one element per line.

    Output:

    C:\Temp> h
    15
    6
    2
    8
    

    The long way of writing essentially the same thing (with less memory consumption) would be:

    my @stack;
    
    while ( my $line =  ) {
        last unless $line =~ /\S/;
        my @values = split ' ', $line;
        push @stack, \@values;
    }
    
    for my $ref ( @stack ) {
        print join("\n", @$ref), "\n";
    }
    

    Finally, if you wanted do something other than printing all values, say, sum all the numbers, you should store one value per element of @stack:

    use List::Util qw( sum );
    
    my @stack;
    
    while ( my $line =  ) {
        last unless $line =~ /\S/;
        my @values = split ' ', $line;
        push @stack, @values;
    }
    
    printf "The sum is %d\n", sum @stack;
    

提交回复
热议问题