in reply to Stupid question about strings...

Hi, Kepler

Try switching your variables in the comparison, ie if ( $str2 =~ /$str1/i ){...

The other issue is that you have pipes at each end of $str1, which will probably interfere with the match (essentially allowing $str2 to always match), so you may want to do something about that (such as removing them, or escaping them, though that will also be problematic)

Replies are listed 'Best First'.
Re^2: Stupid question about strings...
by ww (Archbishop) on Jul 14, 2014 at 10:49 UTC
    C:\>perl -E "my $str1 = qq(|L|D|); my $str2 = qr(\|L\|);if ($str2 =~ $ +str1) { say 'foo';}" foo

    Actually, SimonPratt is right. From OP's description ($str2 ["is in"] as a part of $str1) requires a regex test (if used) in the above order.

    Update: Added direct quote from OP's spec to clarify my paraphase, "as a part of...."


    check Ln42!

      Nope. If you want to know if string2 is in string1, you need string1 on the left side and string2 on the right side of the binding operator.
      $ perl -E 'my $str1 = qq(one two three); my $str2 = qq(two); if ($str +2 =~ m/$str1/) { say "foo";}' $ perl -E 'my $str1 = qq(one two three); my $str2 = qq(two); if ($str +1 =~ m/$str2/) { say "foo";}' foo
      Your test is wrong for the following reason: if you want to try to put string1 on the right side, then it is string1 that should be a quotemetaed regex or have the pipes escaped:
      $ perl -E 'my $str1 = qr(\|L\|D\|); my $str2 = qq(\|L\|); if ($str2 = +~ m/$str1/) { say "foo";}' $ perl -E 'my $str1 = qq(\|L\|D\|); my $str2 = qr(\|L\|); if ($str1 = +~ m/$str2/) { say "foo";}' foo $ perl -E 'my $str1 = qq(|L|D|); my $str2 = qq(|L|); if ($str1 =~ m/\ +Q$str2/) { say "foo";}' foo

        You appear to have (most of) the angels on your side.

        So why did the code I showed return true (or "foo")?"


        Quis custodiet ipsos custodes. Juvenal, Satires

Re^2: Stupid question about strings...
by Anonymous Monk on Jul 14, 2014 at 09:25 UTC
    if ( $str2 =~ /$str1/i ){...

    OP stated that the task is to find $str2 in $str1, so that's probably not right.

    such as ... escaping them, though that will also be problematic

    See davido's answer regarding \Q (as well as quotemeta).

      You're quite right, not sure what I was thinking!