How do I check to see if a scalar has a compiled regex in it with Perl?
Posted
by Robert P
on Stack Overflow
See other posts from Stack Overflow
or by Robert P
Published on 2010-04-01T20:13:14Z
Indexed on
2010/04/01
20:23 UTC
Read the original article
Hit count: 229
Let's say I have a subroutine/method that a user can call to test some data that (as an example) might look like this:
sub test_output {
my ($self, $test) = @_;
my $output = $self->long_process_to_get_data();
if ($output =~ /\Q$test/) {
$self->assert_something();
}
else {
$self->do_something_else();
}
}
Normally, $test
is a string, which we're looking for anywhere in the output. This was an interface put together to make calling it very easy. However, we've found that sometimes, a straight string is problematic - for example, a large, possibly varying number of spaces...a pattern, if you will. Thus, I'd like to let them pass in a regex as an option. I could just do:
$output =~ $test
if I could assume that it's always a regex, but ah, but the backwards compatibility! If they pass in a string, it still needs to test it like a raw string.
So in that case, I'll need to test to see if $test
is a regex. Is there any good facility for detecting whether or not a scalar has a compiled regex in it?
© Stack Overflow or respective owner