Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: How to print the lines immediately above and below a matching line?

by karlgoethebier (Vicar)
on Nov 25, 2012 at 20:35 UTC ( #1005523=note: print w/ replies, xml ) Need Help??


in reply to How to print the lines immediately above and below a matching line?

As far as i understood the basic theme is: "...match a specific part of a line and print the line above and below it, in full." Please correct me if i'm wrong.

I would do it like this:

#!/usr/bin/perl use strict; use warnings; use Tie::File; # my $pattern = qr/(^4000.+)/; # my $pattern = qr/(^4001.+)/; my $pattern = qr/(^4002.+)/; # my $pattern = qr/(4003.+)/; # my $pattern = qr/(^4004.+)/; # my $pattern = qr/(^4005.+)/; tie my @lines, 'Tie::File', shift || die; my $idx = 0; for my $line(@lines){ print qq($idx $line\n); if( $line =~ m/($pattern)/ ){ if( $idx == 0){ print qq(Heuraka: $1 next: $lines[ ( $idx + 1) ]\n); }; if ( $idx == scalar( @lines - 1 ) ) { print qq(Heuraka: $1 previous: $lines[ ( $idx - 1 )] \n); }; if ( $idx ~~ [ 1..scalar( @lines - 2 ) ]) { print qq(Heuraka: $1 previous: $lines[ ( $idx - 1 ) ] next: +$lines[ ( $idx + 1 ) ]\n); }; } ++$idx; } untie @lines || die; __END__ Karls-Mac-mini:Desktop karl$ cat MyData.txt 4000_1#0 4001_1#1 4002_1#2 4003_1#3 4004_1#4 4005_1#5 Karls-Mac-mini:Desktop karl$ ./test.pl MyData.txt 0 4000_1#0 1 4001_1#1 2 4002_1#2 Heuraka: 4002_1#2 previous: 4001_1#1 next: 4003_1#3 3 4003_1#3 4 4004_1#4 5 4005_1#5

See also: Tie::File

Regards, Karl

«The Crux of the Biscuit is the Apostrophe»


Comment on Re: How to print the lines immediately above and below a matching line?
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2015-07-07 01:48 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 (86 votes), past polls