
BillKSmith
Veteran
Aug 28, 2017, 11:33 AM
Post #2 of 6
(3118 views)
|
Re: [tsdjim] Select lines in a file between pattern
[In reply to]
|
Can't Post
|
|
There is nothing wrong with your logic. If you had used strict and warnings, you would have received an error message referring to the offending statement. (Your print statement is trying to print back to the input file.) I have replaced your disk file with an in-memory file in order to show the data in the post.
C:\Users\Bill\forums\guru>type tsdjim0.pl my $random_file = \<<'END_RANDOM_FILE'; Auguststart Some text some more text Augustend Septemberstart Some text some more text Septemberend END_RANDOM_FILE my ( $day, $month, $year ) = ( localtime )[3,4,5]; $month = ( qw/ January February March April May June July August September October November December / )[$month]; $monthx = $month . 'start'; $monthy = $month . 'end'; open(SESAME, '<', $random_file); while (<SESAME>) { if (/^$monthx/../^$monthy/) {print }; } close (SESAME) or die "Could not close sample.txt: $!"; C:\Users\Bill\forums\guru>perl tsdjim0.pl Auguststart Some text some more text Augustend I recommend several changes to improve the style. Always use strict and warnings Always use three-argument form of open Always check open for failure. Always use lexical (my) file-handles Format your code with perltidy Here is an improved version of your code:
use strict; use warnings; my $random_file = \<<'END_RANDOM_FILE'; Auguststart Some text some more text Augustend Septemberstart Some text some more text Septemberend END_RANDOM_FILE my $month = (qw/ January February March April May June July August September October November December / )[(localtime)[4]]; my $monthx = $month . 'start'; my $monthy = $month . 'end'; open( my $SESAME, '<', $random_file ) or die "Cannot open input file\n:$!"; while (<$SESAME>) { print if /^$monthx/ .. /^$monthy/ ; } close($SESAME) or die "Could not close sample.txt: $!"; Good Luck, Bill
|