http://www.perlmonks.org?node_id=665415


in reply to ref() and Regexp

You shouldn't ever have to think about what string ref() returns. By comparing it to a prototype of the same thing, you insulate yourself from version changes and thinkos (like me forgetting if it's REGEX, REGEXP, Regex, or Regexp):

if( ref $regex eq ref qr// ) { ... }

Or, hide that in a subroutine is_regex() or something similar.

--
brian d foy <brian@stonehenge.com>
Subscribe to The Perl Review

Replies are listed 'Best First'.
Re^2: ref() and Regexp
by ikegami (Patriarch) on Jan 31, 2008 at 20:02 UTC

    Or, hide that in a subroutine is_regex() or something similar.

    Like this?

    BEGIN { if (!defined(&re::is_regexp)) { package re; my $re_class = ref qr//; *is_regexp = sub($) { local *__ANON__ = 'is_regexp'; return UNIVERSAL::isa($_[0], $re_class); }; } }

    Using your philosophy to avoid magical constants, it checks if re::is_regexp is defined rather than checking $] for 5.10.

    BEGIN and the prototype duplicates the behaviour of 5.10's re::is_regexp.

    It uses isa instead of ref so regexes can be made detectable even if there's a need to rebless the regex (by adding Regex to that class's @ISA). It's not an invitation for non-regexes to pretend to be regexes.

Re^2: ref() and Regexp
by Anonymous Monk on Sep 13, 2009 at 10:37 UTC
    Wouldn't qr/FOO/ be cheaper? (an empty regex is special)
      an empty regex is special
      In a match (see m//), but not for qr//:
      $ perl -e 'print qr//;' (?-xism:)