mr_mischief has asked for the wisdom of the Perl Monks concerning the following question:

Am I just crazy today, or is the behavior of this one-liner strange?
echo 'abcdef g' | perl -e '$_ = <>; print if m/[a-g]+\n/'
It prints the line. Should it? What's matching the space?

Here's my perl -v:

# perl -v This is perl, v5.8.7 built for i686-linux-ld Copyright 1987-2005, Larry Wall Perl may be copied only under the terms of either the Artistic License or the GNU General Public License, which may be found in the Perl 5 source kit. Complete documentation for Perl, including FAQ lists, should be found on this system using `man perl' or `perldoc perl'. If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page.


Christopher E. Stith

Replies are listed 'Best First'.
Re: Is thie a regex strangeness?
by ikegami (Patriarch) on Jan 31, 2006 at 18:41 UTC

    Replace
    m/[a-g]+\n/
    with
    m/^[a-g]+\n$/
    It was matching the "g\n" part of the input string.

    By the way, it's <code> (or <c>), not [code].

      Ah! How embarrassing. Yes, that makes perfect sense. It's been an off-kilter day all around.

      Sorry for the tag confusion on my part. I've been mostly away from the site for a long while.


      Christopher E. Stith
Re: Is this a regex strangeness?
by blazar (Canon) on Feb 01, 2006 at 10:55 UTC

    Indeed it matches a sequence of one or more charachters in the range [a-g] next to the newline. Precisely "g\n". In case of doubt although there's a case against $& ;-) you may try printing that to see what matched. Or else put a pair of capturing parens and print $1 which amounts to fundamentally the same thing. Or even use the return value of the match:

    $ perl -pe '($_)=/[a-g]+\n/g' abcdef g g