in reply to Chomping Frenzy question

$str =~ s/(?:\Q$chompstr\E)+\z//;

Or use the quotemeta builtin.

By the way you'd have to use chomp and not chop, because the latter unconditionally chops off the last character, whereas chomp removes $/.

Replies are listed 'Best First'.
Re^2: Chomping Frenzy question
by rovf (Priest) on Jul 10, 2008 at 14:14 UTC
    $str =~ s/(?:\Q$chompstr\E)+\z//;

    Wouldn't this also fail if $chompstr contained \E ?

    Or use the quotemeta builtin.

    This is nice! I had used this function a few years ago, but meanwhile forgotten it.

    By the way you'd have to use chomp and not chop

    Of course, you are right. I was too careless when sketching my solutions...

    -- 
    Ronald Fischer <ynnor@mm.st>
      Wouldn't this also fail if $chompstr contained \E ?

      No, it's magic:

      use strict; use warnings; my $str = 'foo\E**** <- this is a syntax error'; if ("foo" !~ m/\Q$str\E/){ print "No syntax error\n"; } __END__ No syntax error

      If the quoting had stopped by the embedded \E, you'd get the Nested quantifiers in regex error.

      Wouldn't this also fail if $chompstr contained \E ?

      No. That confused me when I first heard of \Q..\E too.

      • \Q..\E doesn't prevent interpolation.
      • \E isn't special in interpolated strings. It matches the two characters. "\" and "E"
      • $ don't trigger interpolation in interpolated strings. It matches end of lines.