tags:

views:

284

answers:

3

I'm reading a regular expression from a configuration file, which may or may not have invalid syntax in it. (It's locked down behind a firewall, so let's not get into security.) I've been able to test for a number of errors and give a friendly message.

No such luck on this one:

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 it has resisted my efforts to check for this condition.

So the question is: does anybody know how to capture this? Do I have to redirect STDERR?

+1  A: 

Here is how to turn this warning to an error:

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

Here is how to ignore this warning:

sub un {
  local $SIG{__WARN__} = sub {
    print STDERR $_[0] if $_[0]!~/^Unrecognized escape /;
  };
  qr{$_[0]}
}
un('al\Fa');
print "Reached.\n";
pts
to ignore a warning it is better to use "no warnings 'warning_category';"
Alexandr Ciornii
A: 

Since it's a warning, you'd need to redirect STDERR as well.

My guess is you're getting the warning because you're interpolating the regex string you get from the configuration file - try s/\\/\\\\/g on the regex string before using it.

bubaker
Oops, that's what I meant: STDERR -- actually on first typing it was STOUT. :D
Axeman
+3  A: 

You can make the warning FATAL and use block eval:

#!/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";
Sinan Ünür
worked for me, thanks.
Axeman