perl - Why does a match against regex $ return 1 when the input string contains a newline? -


why command

perl -e "print qq/a\n/ =~ /$/" 

print 1?

as far know, perl considers $ position both before \n position @ end of whole string in multi-line mode, default (no modifier applied).

the match operator returns 1 true value because pattern matched. print outputs value.

the $ anchor, specific sort of zero-width assertion. matches condition in pattern consumes no text. since have nothing else in pattern, /$/ matches target string including empty string. return true.

the $ end-of-line anchor, documented in perlre. $ allows vestigial newline @ end, both of these can match:

"a"   =~ /a$/ "a\n" =~ /a$/ 

without /m regex modifier, end of line end of string. but, modifier can match before newline in string:

"a\n" =~ /a$b/m 

you might behavior if don't see attached particular match operator since people can set default match flags:

use re '/m'; # applies in lexical scope 

over-enthusiastic fans of perl best practices make trio of pattern changing commands default (often not auditing every regex affects):

use re '/msx' 

there's anchor, end-of-string anchor \z, allows trailing newline. if don't want allow newline, can use lowercase \z mean absolute end of string. these not affected regex flags.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -