Can I catch the “Unrecognized escape” warning when compiling a regular expression?

I am reading a regular expression from a configuration file, which may or may not have invalid syntax. (It’s blocked behind a firewall, so don’t enter the security system.) I was able to check many errors and give a friendly message.

There is no such luck on this:

Unrecognized escape \Q passed through in regex

I know what causes it, I just want to know if I can capture it in Perl 5.8. So far, he has resisted my efforts to test this condition.

So the question is: does anyone know how to fix this? Do I need to redirect STDERR?

+3
source share
3 answers

You can make a FATAL warning and use the eval block:

#!/usr/bin/perl

use strict;
use warnings;

my $s = '\M';

my $r = eval {
    use warnings FATAL => qw( regexp );
    qr/$s/;
};

$r or die "Runtime regexp compilation produced:\n$@\n";
+3

:

sub un {
  local $SIG{__WARN__} = sub {
    die $_[0] if $_[0]=~/^Unrecognized escape /;
    print STDERR $_[0]
  };
  qr{$_[0]}
}
un('al\Fa');
print "Not reached.\n";

:

sub un {
  local $SIG{__WARN__} = sub {
    print STDERR $_[0] if $_[0]!~/^Unrecognized escape /;
  };
  qr{$_[0]}
}
un('al\Fa');
print "Reached.\n";
+1

Since this is a warning, you need to redirect as well STDERR.

I assume that you are getting a warning because you are interpolating the regular expression line that you get from the configuration file - try s/\\/\\\\/gthe regular expression line before using it.

0
source

Source: https://habr.com/ru/post/1708770/


All Articles