http://www.perlmonks.org?node_id=1060731


in reply to Perl: How to match a line and print words at line immediately above it?

The way I iterate through an array and keep track of the previous element is like so:

my $previous = ''; foreach my $line (@arrayfile) { if ($line =~ m/WhateverIWantToMatch/) { print "$previous\n" if ($previous); } $previous = $line; #### This line now becomes the previous line for + the next array element seeing as ALL lines in the file will be proce +ssed }

This is a quick example and presumes you are not going to find a match on the first line of the file.
  • Comment on Re: Perl: How to match a line and print words at line immediately above it?
  • Download Code

Replies are listed 'Best First'.
Re^2: Perl: How to match a line and print words at line immediately above it?
by sundialsvc4 (Abbot) on Nov 01, 2013 at 14:59 UTC

    ... or perhaps my $previous = undef; to clearly reflect that there is no previous-line, much as NULL (in a database column) denotes the complete absence of any value at all.   Whatever makes the most sense in your particular situation.