1

I would like to write a Perl subroutine that takes either a string value or a regex value as a parameter and do different things depending on the result. For the sake of this question it simply returns "regex" if it is a regex value and "string" if it is not a regex:

sub value_string_or_regex {
    my ($value) = @_;
    my $result = '';
    # magic here
    return $result;
}

So the following code would print out "string":

print(value_string_or_regex("hello world") . "\n");

And the following code would print out "regex":

print(value_string_or_regex(qr/^.*world$/) . "\n");
Yoshiya
  • 452
  • 5
  • 17

1 Answers1

1

I recommend against that since that which "hello\s+world" returns is as much of a regex pattern as that which qr/hello\s+world/ returns.

That said, you can use builtin re::is_regexp to check if a scalar contains a regex pattern compiled by qr.

ikegami
  • 367,544
  • 15
  • 269
  • 518