Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

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 (Canon) 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?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2018-08-16 15:34 GMT
Find Nodes?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:

    Results (168 votes). Check out past polls.