Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
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 (Monsignor) 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 meditating upon the Monastery: (8)
As of 2014-08-27 23:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (253 votes), past polls