perl5 icon indicating copy to clipboard operation
perl5 copied to clipboard

Regex with closing square bracket but no opening bracket is parsed

Open robrwo opened this issue 6 months ago • 3 comments

Description

The following Regex is accepted in Perl 5.40.2 but from my brief testing this is also accepted as far back as 5.14. (Possibly earlier)

my $re = qr/\n\r\s]+/;

This was a typo that omitted the opening square bracket. It should not have parsed.

Steps to Reproduce

Above

Expected behavior

This should return an error like "Unmatched ] in regex"

robrwo avatar May 29 '25 11:05 robrwo

Weirdly,

use re qw(strict);
qr/]/

is fine, but

use re qw(strict);
qr/]]/

is an error (Unescaped literal ']' in regex; marked by <-- HERE in m/]] <-- HERE /). If anything, this is a bug in re 'strict'.

The default behavior is not a bug, but documented as a feature in https://perldoc.perl.org/perlre#:~:text=sometimes%20metacharacter:

The matching "]" is also a metacharacter; again it doesn't match anything by itself, but just marks the end of your custom class to Perl. It is an example of a "sometimes metacharacter". It isn't a metacharacter if there is no corresponding "[", and matches its literal self:

print "]" =~ /]/;  # prints 1

mauke avatar May 29 '25 12:05 mauke

It looks like re-strict-mode https://metacpan.org/pod/re#%27strict%27-mode hex characters.

robrwo avatar May 29 '25 13:05 robrwo

"Unescaped literal" is a bizarre thing to say - You're telling me you already know it's a literal, but I still have to escape it for it to be treated as a literal? Even when it couldn't mean anything else? Dunno man, sounds sketchy.

guest20 avatar May 29 '25 15:05 guest20