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»