raghuprasad241 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I have a text file of the following format. I modified the contents of the file.

cat temp This is little Monk and he is a sharp kid He is on a mountain!

In the above text there are two separate lines and they are separated by a new line. I am trying to match for e.g. kid <followed by a newline> He

To accomplish this I am using the following regular expression, I am using a single line modifier when used perl should match any character for a dot(.) including new line. I am trying to capture the match to a special variable $&. My $& should print "kid<newline>He". So what am I missing here ?

perl -ne 'use v5.10; say $& if (/kid.He/s);' temp <No output> perl -ne 'use v5.10; say $& if (/kid/s);' temp kid perl -ne 'use v5.10; say $& if (/He/s);' temp He
Appreciate all the monks for looking at this.

Replies are listed 'Best First'.
Re: dot(.) metacharacter in single line modifier mode
by raghuprasad241 (Beadle) on Mar 04, 2016 at 19:08 UTC

    Sorry for troubling you monks. I figured out the answer for my stupid question. I need to read the file in the paragraph mode to get the desired result.

    I tried the following and it is working as expected.

    perl -00 -ne 'use v5.10; say $& if (/kid.He/s);' temp kid He
    Thanks!
Re: dot(.) metacharacter in single line modifier mode
by stevieb (Canon) on Mar 04, 2016 at 19:13 UTC

    First, you're using -e but using say which won't work. For the say feature, you need -E. Bah... the v5.10 was right in front of me even.

    Second, you're only reading one line of the file at a time (-n), so you'll never see the "He" on the next line.

    Try something like this, which slurps in the entire file all at once:

    perl -E '$str=do{local($/);<>}; say $& if $str =~ /kid.He/s;' temp kid He

    ps. I didn't know about the -00 flag :)