match pattern of multiple lines

J

John Black

Hi,
I need to match the following pattern with a file,

begin <some string>
<some thing this line>
<some thing this line>
......
end

I check the web, it says I should use pattern modifier s & m, so I
write it this way,

while (<MyFile>){
if (/^(\s*)begin(.*)^(\s*)end/smi){
... call my function...
}
}

But it never matches the pattern, do you see the problem?

Thanks!
 
G

Gunnar Hjalmarsson

John said:
while (<MyFile>){
if (/^(\s*)begin(.*)^(\s*)end/smi){
... call my function...
}
}

But it never matches the pattern, do you see the problem?

If you haven't set the $/ variable, you are only testing one line at a
time. One solution is to slurp the file instead of using a while loop:

local $_ = do { local $/; <MyFile> };
 
M

Mohammad Mahmoud Khajah

Hi,
I need to match the following pattern with a file,

begin <some string>
<some thing this line>
<some thing this line>
......
end

I check the web, it says I should use pattern modifier s & m, so I
write it this way,

while (<MyFile>){
if (/^(\s*)begin(.*)^(\s*)end/smi){
... call my function...
}
}

But it never matches the pattern, do you see the problem?

Thanks!

Hi,

This won't work because you are reading the file one line at a time. You
may want to read the whole file at one time by using this:

local $/; # slurp mode ( to read the file into a string )
my $content = <MyFile>;

if ( $content =~ /^\s*begin\s+(.+?)\s+end$/smi ) { CallFunc(); }

Also, check the regular expression you are using as it doesn't seem
to be right. I've modified it in the example above but I'm not sure if it
is what you want.

Note that reading the file at one time can be memory-intensive if the file
is too big.

good luck,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top