Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: ref() and Regexp

by brian_d_foy (Abbot)
on Jan 31, 2008 at 18:27 UTC ( #665415=note: print w/replies, xml ) Need Help??

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 <>
Subscribe to The Perl Review

Replies are listed 'Best First'.
Re^2: ref() and Regexp
by ikegami (Pope) 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:)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://665415]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2021-04-10 14:42 GMT
Find Nodes?
    Voting Booth?

    No recent polls found