Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Empty Regex never fails but failed?

by leszekdubiel (Sexton)
on Feb 12, 2018 at 23:07 UTC ( #1209030=perlquestion: print w/replies, xml ) Need Help??
leszekdubiel has asked for the wisdom of the Perl Monks concerning the following question:

I am completely confused why this fails:
printf "alfa\nwhatever" | perl -CSDA -n -e '// or die "not possible! - +- $_ --"; /alfa/;'
Die should never happen because empty pattern matches any text... Why? Why? Same on 5.24 and 5.26. Linux Debian. The code
printf "alfa\nwhatever" | perl -CSDA -n -e '// or die "not possible! - +- $_ --"; /al/;'
also fails, but this one not (!!!!):
printf "alfa\nwhatever" | perl -CSDA -n -e '// or die "not possible! - +- $_ --"; /a/;'

Replies are listed 'Best First'.
Re: Empty Regex never fails but failed?
by haukex (Abbot) on Feb 12, 2018 at 23:22 UTC
    See Regexp Quote Like Operators:

    The empty pattern //

    If the PATTERN evaluates to the empty string, the last successfully matched regular expression is used instead. In this case, only the g and c flags on the empty pattern are honored; the other flags are taken from the original pattern. If no match has previously succeeded, this will (silently) act instead as a genuine empty pattern (which will always match).

    That's why your third example works: /a/ matches in both alfa and whatever.

    $ printf "Foo\nBar\nQuz\nBaz" | perl -nle 'print // ?"yes":"no"; /a/' yes yes no yes

    (See also Repeated Patterns Matching a Zero length Substring, although I think that's less relevant in this case.)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1209030]
Approved by hippo
Front-paged by GrandFather
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2018-05-24 19:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?