Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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

by Doozer (Scribe)
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

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1060731]
help
Chatterbox?
[Lady_Aleena]: geany may not support that.
[shmem]: I see that there is a plugin geany-plugin- codenav
[shmem]: maybe that supports ctags, check the documentation
[Lady_Aleena]: I'd have to talk to a geany person to see.
[Lady_Aleena]: Right now, I'm trying to decide whether I want to rewrite how variables are entered in the sub I'm working on.
[shmem]: wait, what? you want that person to read the documentation for you?
[Lady_Aleena]: I might have to go with options instead of a straight list.
[Discipulus]: if more than 3 go for named variables LA
[Lady_Aleena]: Discipulus, it is at 2 now, but with what I am thinking about, it could go to 3. However, only 1 is needed. The second and third are optional.
[shmem]: straight list or named parameters - that depends on whether (and how many) optional arguments you have

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (13)
As of 2017-04-27 12:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (506 votes). Check out past polls.