in reply to Pattern matching regex problem

You are NOT using "pattern matching regex", you are using transliteration.

 $s =~ tr/[IOSM]//c says to translate every character NOT in the list '[', 'I', 'O', 'S', 'M' or ']' to itself, and as a side effect return the count of characters modified.

So the string in $s does not contain any characters that are not in the list '[', 'I', 'O', 'S', 'M' or ']'.

Replies are listed 'Best First'.
Re^2: Pattern matching regex problem
by Anonymous Monk on Nov 23, 2021 at 09:05 UTC
    Ok, I see the difference. So, how would I tell it to print 'case 1' if 'M' is present, and 'case 2' if it's not?

      If all you want to do is check the presence of M using tr/// then it is simple:

      #!/usr/bin/env perl use strict; use warnings; my $s='IIIIIIIIIIIIIIIIIIIIIIIIIIOOOOOSSSSS'; print "$s: " . ($s =~ tr/M/M/ ? "case1\n" : "case2\n"); $s .= 'M'; print "$s: " . ($s =~ tr/M/M/ ? "case1\n" : "case2\n");

      🦛

        Or, if you don't care about tr///:

        if ($s =~ /M/) { print "case1\n"; } else { print "case2\n"; }

        tr/M// is sufficient.