Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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

by Doozer (Beadle)
on Nov 01, 2013 at 09:57 UTC ( #1060731=note: print w/ replies, xml ) Need Help??


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
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1060731]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2015-07-05 04:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls