Reputation: 22994
The -n
argument causes Perl to place a loop around the program, which makes it iterate over filename arguments somewhat like sed -n
or awk
.
Now, is it possible to skip grab some of the forthcoming lines lines in advance in script using -n
?
#!/usr/bin/perl -wn
if (/my case/) {
# Skip two lines
<>; <>;
# Do something with the line just read.
}
The above is not working for me. $_
is stuck at the same line/content.
Upvotes: 1
Views: 121
Reputation: 385647
Another approach is to use a sliding window buffer.
perl -ne'
push @buf, $_;
next if @buf <= 3;
shift(@buf);
if ($buf[0] =~ /c/) {
my $line1 = $buf[1];
my $line2 = $buf[2];
...
}
'
Upvotes: 1
Reputation: 241828
It works for me:
perl -wE 'say for 1..10' | perl -ne 'if (/2/) { <>; <>; print "!$_" } else { print }'
1
!2
5
6
7
8
9
10
If you want to process the next two lines, store them in variables.
$line1 = <>; $line2 = <>;
<>
on its own doesn't populate $_
- only in the special case of while (<>)
.
Upvotes: 3