in reply to Parsing text file question

chomp( my @array = <FILE> ); foreach my $previous_line_no ( 0 .. $#array ) { # count through the ar +ray. # runs over its bounda +ry, hmm. # see with warnings on +. my $line_no = $previous_line_no + 1; if ( $array[$line_no] =~ m/fail/ ) { splice( @array, $previous_line_no, 1 ); # take that previous l +ine out. } }

Cheers, Sören

Replies are listed 'Best First'.
Re^2: Parsing text file question
by integral (Hermit) on Jun 28, 2004 at 08:27 UTC

    How about using redo and a c-style for loop?

    my (@array, $i); @array = <FILE>; for ($i = 0; $i <= $#array; $i++) { if ($i > 0 and $array[$i] =~ /\bfail\b/) { splice @array, $i - 1, 1; redo; } }

    --
    integral, resident of freenode's #perl
    
Re^2: Parsing text file question
by neniro (Priest) on Jun 28, 2004 at 08:31 UTC
    Hi Sören,
    you can do this in one step:
    chomp (my @lines = grep (!/^fail/, <>));
    neniro
      Thanks all for replies. Neniro. It looks like your code suggestion will put all lines except those starting with "fail" to @lines array. What I need is to take out is the 1 line exactly above the fail. Thanks again.
        Sorry, I missed the task. The following should work:
        #!/usr/bin/perl use strict; use warnings; use Data::Dumper; chomp (my @lines = <>); for (0..$#lines) { $lines[$_-1] = undef if ($lines[$_] =~ /fail/)}; @lines = grep (defined, @lines); print Dumper \@lines;