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.