Previous Page
Next Page

12.4. End of String

Use \z, not \Z, to indicate "end of string".

Perl provides a variant of the \z marker: \Z. Whereas lowercase \z means "match at end of string", capital \Z means "match an optional newline, then at end of string". This variant can occasionally be convenient, if you're working with line-based input, as you don't have to worry about chomping the lines first:

    
    # Print contents of lines starting with --...
    LINE:
    while (my $line = <>) {
        next LINE if $line !~ m/ \A -- ([^\n]+) \Z/xm;
        print $1;
    }

But using \Z introduces a subtle distinction that can be hard to detect when displayed in some fonts. It's safer to be more explicit: to stick with using \z, and say precisely what you mean:


    

    # Print contents of lines starting with --...
LINE: while (my $line = <>) { next LINE if $line !~ m/ \A -- ([^\n]+) \n? \z/xm;
# Might be newline at end
print $1; }

especially if what you actually meant was:


    

    # Print contents of lines starting with -- (including any trailing newline!)...
LINE: while (my $line = <>) { next LINE if $line !~ m/ \A -- ([^\n]* \n?) \z/xm; print $1; }

Using \n? \z instead of \Z forces you to decide whether the newline is part of the output or merely part of the scenery.

    Previous Page
    Next Page