that_perl_guy has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks,
I will be extremely thankful if the monks here could help me understanding regex in Perl.
Suppose I have a text file that has these lines:
This is line one. Line Two is this. Third line starts here. This is line four. This is line five. This is line six. This is the seventh line. This is line eight.
If the record contains the word "third" our "four", I want it to print the whole record, meaning the stuff between the empty lines, not just lines with those words in it. But I am not able to write it correctly. Here is what I have tried:
use strict; use warnings; open my $fh, "+<", "testlines.txt"; while (<$fh>) { if ($_=~ /(third | four)/si) { chomp; local $/ = "\n\n"; print "line is: $_\n"; } }
And it prints:
>perl regex.pl line is: Third line starts here. line is: This is line four.
But what I want is:
This is line one. Line Two is this. Third line starts here. This is line four
Where am I going wrong? Please guide. Please note, this is just an example. Depending on the data supplied the other lines in the file may contain some different words.
Not sure if this matters, but I'm on Windows 10 with Strawberry Perl version 5.32.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Question about regex.
by GrandFather (Saint) on Sep 29, 2020 at 03:07 UTC | |
Re: Question about regex.
by NetWallah (Canon) on Sep 29, 2020 at 02:45 UTC | |
Re: Question about regex.
by Cristoforo (Curate) on Sep 29, 2020 at 03:36 UTC | |
Re: Question about regex. ($INPUT_RECORD_SEPARATOR)
by LanX (Saint) on Sep 29, 2020 at 11:12 UTC | |
Re: Question about regex.
by haukex (Archbishop) on Sep 29, 2020 at 18:11 UTC | |
by GrandFather (Saint) on Sep 29, 2020 at 20:11 UTC | |
by haukex (Archbishop) on Sep 29, 2020 at 20:32 UTC | |
by GrandFather (Saint) on Sep 30, 2020 at 00:45 UTC | |
by haukex (Archbishop) on Sep 30, 2020 at 07:17 UTC | |
by hippo (Archbishop) on Sep 30, 2020 at 09:03 UTC | |
| |
Re: Question about regex.
by that_perl_guy (Initiate) on Sep 29, 2020 at 04:14 UTC | |
by AnomalousMonk (Archbishop) on Sep 29, 2020 at 04:29 UTC |