sashac88 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Monks! I have to parse a text file. I put every line as variable in array. foreach (readline FILE) { push @array,$_} So far OK. Now If I see a line with the word "fail".Then I'd like to disregard the preceding line-so it won't appear in the array. How can I achieve that. Thank you very much in advance..

Replies are listed 'Best First'.
Re: Parsing text file question
by Aragorn (Curate) on Jun 28, 2004 at 09:03 UTC
    Another way of doing this:
    #!/usr/local/bin/perl use strict; use warnings; my @lines_ok = (); while (<DATA>) { chomp; pop @lines_ok, next if /fail/; push @lines_ok, $_; } print join(", ", @lines_ok); __DATA__ line 1 line 2 line 3 fail line 4 line 5
    Arjen
      This also excludes lines that have "fail" in them, which is not specified in the OP. Remove the "next" phrase from the "pop" line and I think you've got it.
Re: Parsing text file question
by Happy-the-monk (Canon) on Jun 28, 2004 at 08:23 UTC

    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

      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
      
      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.
Re: Parsing text file question
by neniro (Priest) on Jun 28, 2004 at 08:16 UTC
    Show us the related snippet of your code. It's much easier to help you, if we knew what you're exactly doing.
      open FILE,"$commandfile"; foreach (readline FILE1) { if (/error occurred/) { s/.*//; } push @start_from, $_; }
      FILE has many commands in it.If I see a line with comand "exit" on it-then I have to ignore the preceding line,i.e. not to put it in @start_from. Thanks

      Edited by Chady -- code tags.