in reply to Extracting Lines of a text file

I suppose I'd do it like this;
#!/usr/bin/perl use strict; use warnings; my $filename = "C:/FolderA/test.txt"; # default input file if ( @ARGV > 1 and -f $ARGV[1] ) { $filename = pop; # alternatively, get input file from command lin +e } my $pattern; if ( @ARGV ) { $pattern = shift; # get search pattern from command line } else { die "Usage: $0 search_pattern_regex [input.filename]\n"; } open( FILE, "<", $filename ) or die "Open failed on $filename: $!"; my @line_buffer; while (<FILE>) { push @line_buffer, $_; shift @line_buffer if ( @line_buffer > 3 ); print join( "", @line_buffer, "\n" ) if ( @line_buffer > 1 and $line_buffer[-2] =~ /$pattern/ ); } print join( "", @line_buffer ) if ( $line_buffer[-1] =~ /$pattern/ ); close FILE;
Some points to consider: Note that the gnu "grep" tool (available for windows via cygwin and other "unix-utils-for-windows" packages) already does what you are trying to do here, so unless there's some perlish capability you want to add that the standard gnu grep doesn't have, there's no need to reinvent this wheel.