You can use an array as a print buffer. A.
my @array; while (<DATA>) { push @array, $_; shift @array if @array > 4; print @array if /script/; } __DATA__ 1 I am here 2 to work in 3 Perl for writing 4 a script for 5 myself
Various uses:
If you intend to use this as standalone, you can use grep instead:
grep -B3 script xx.txt
Or perl one-liner if grep not a parameter (for example, you are on Windows):
perl -nwe 'push @a, $_; shift @a if @a > 4; print @a if /script/' xx.txt
If it is inside a script, you only need to specify your own file descriptor:
my @array; open my $fh, '<', "xx.txt" or die $! while (<$fh>) { push @array, $_; shift @array if @array > 4; print @array if /script/; }
source share