Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Reading particular line which repeats itself many times in text

by chessgui (Scribe)
on Jan 28, 2012 at 08:30 UTC ( #950489=note: print w/ replies, xml ) Need Help??


in reply to Reading particular line which repeats itself many times in text

I don't know whether there is a fancy regular expression for this but in case where there are blocks I always use split (I consider it safer).

my @begin_blocks=split /BEGIN $name/,$string_containing_blocks; my $block=$begin_blocks[1]; $block=~s/END\s*$//;
If there is no match '' is returned (since @begin_blocks now has only the zero index element: the string itself). This won't work if BEGIN blocks can contain the string 'BEGIN' inside them. If this is necessary you can use an escape sequence: replace all 'BEGIN'-s inside the block with 'BEGIN_'. If such a coding is used the search looks like this (add one line for decoding BEGIN_):
my @begin_blocks=split /BEGIN $name/,$string_containing_blocks; my $block=$begin_blocks[1]; $block=~s/END\s*$//; $block=~s/BEGIN_/BEGIN/g;


Comment on Re: Reading particular line which repeats itself many times in text
Select or Download Code
Re^2: Reading particular line which repeats itself many times in text
by uday_sagar (Scribe) on Jan 31, 2012 at 04:35 UTC

    Monks, Thanks for your replies. I have solved the problem by putting together the concepts of non greedy quantifier(?) and storing the whole file (using File::Slurp) in a scalar variable. Here is the code.

    use File::Slurp; local $/ = undef; open FILE, "my_text.txt" or die "Couldn't open file: $!"; binmode FILE; $string = <FILE>; close FILE; if ($string=~/BEGIN hi(.*?)END/s) { print ${1}."\n"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://950489]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2015-07-06 02:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (69 votes), past polls