C:\>perl -E "my $str1 = qq(|L|D|); my $str2 = qr(\|L\|);if ($str2 =~ $ +str1) { say 'foo';}" foo
So why did the code I showed return true (or "foo")?"

Because the string defining the regex used in the  $str2 =~ $str1 expression (i.e., $str1) has the empty pattern as two (!) of its alternatives, and the empty pattern matches everything.

my $str1 = qq(|L|D|); has the empty pattern twice. It doesn't really matter what else is present. The stringization of the output of the  qr(\|L\|) expression is a bit complex, but it could be anything.

c:\@Work\Perl>perl -wMstrict -le "my $str1 = qq(|L|D|); my $str2 = qr(\|L\|); print qq{stringization of qr// output: '$str2'}; if ($str2 =~ $str1) { print 'foo'; } " stringization of qr// output: '(?^:\|L\|)' foo c:\@Work\Perl>perl -wMstrict -le "my $str1 = qq(|X|Y|); my $str2 = qr(\|L\|); if ($str2 =~ $str1) { print 'foo'; } " foo c:\@Work\Perl>perl -wMstrict -le "my $str1 = qq(|X|Y|); my $str2 = qq(aaaaa); if ($str2 =~ $str1) { print 'foo'; } " foo

Update: Changed  my $str2 = qq(xyzzy); in third code example above to  qq(aaaaa) to eliminate any question of case-insensitive matching.


In reply to Re^5: Stupid question about strings... by AnomalousMonk
in thread Stupid question about strings... by kepler

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.