in reply to How to match a ;

You also need to make sure that $line is clean of final new lines whitespace, otherwise your regex won't match your line because $line will end in a new line whitespace instead of ';' - see http://perldoc.perl.org/functions/chomp.html. Also you might consider /^;\s*$/ to strip trailing whitespace.

Syntax wise, your regex is fine.

Best, beth

Update:Correction (see jwkrahn and Grandfather below).

Replies are listed 'Best First'.
Re^2: How to match a ;
by GrandFather (Saint) on Feb 08, 2009 at 09:06 UTC

    Actually no. $ matches an end of line, which may be a \n character. Consider:

    my $line = ";\n"; print $line =~ /$_/ ? "" : "no ", "match: $_\n" for '^;$', '^;', "^;\\ +z";

    Prints:

    match: ^;$ match: ^; no match: ^;\z

    Note that \z matches the physical end of the string.


    Perl's payment curve coincides with its learning curve.
      The  $ regex metacharacter will "[m]atch the end of the line (or before newline at the end)" (emphasis added, perlre section Regular Expressions).

      In the presence of the /m regex modifier, the behavior of  $ is enhanced.

      I stand corrected, but it was actually '.' and '$' new line behavior I was confusing. I once spent a great deal of time beating my brains out until I figured out that '.' doesn't match \n unless you use the 's' modifier, e.g. /;./s. But the more I think about it, I also am finding '$' less clearer than I thought, but I'll save those questions for another thread.

      Best, beth

      Update 2: removed update 1, appears I still have '$' questions and will need to go to SOPW

      I'm puzzled as to why you switched to double quotes and then had to escape the backslash in your third pattern. Sticking to single quotes or using qw{ ... } would have obviated that need.

      $ perl -le ' > $line = qq{;\n}; > print > $line =~ m{$_} > ? q{} > : q{no }, > qq{match $_} > for q{^;$}, q{^;}, q{^;\z};' match ^;$ match ^; no match ^;\z $ perl -le ' $line = qq{;\n}; print $line =~ m{$_} ? q{} : q{no }, qq{match $_} for qw{ ^;$ ^; ^;\z };' match ^;$ match ^; no match ^;\z $

      Cheers,

      JohnGG

        In some places I like DWIM, in other contexts I like to be explicit. In this case I thought being explicit about how the \ gets handled was probably a good thing™.


        Perl's payment curve coincides with its learning curve.
Re^2: How to match a ;
by jwkrahn (Abbot) on Feb 08, 2009 at 08:58 UTC

    The $ anchor will match the end of the line with or without a newline at the end so /^;$/ will match both ";" and ";\n".