in reply to Get regexp modifiers

I've got the gut-feeling, that this is bad advice and there's a better way to do it... but the following works here...

use strict; # print RE into variable and examine it... sub is_ci { my $check_re = shift; die "$check_re is not a RE" if ref $check_re ne 'Regexp'; open my $redir , '>', \my $output; print $redir $check_re; close $redir; return $output =~ /i.*?\-/; # i before '-' } my $r1 = qr/hello/i; my $r2 = qr/hello/; print "true is " , is_ci($r1) ? 'true' : 'false' , " ?\n"; # true print "false is " , is_ci($r2) ? 'true' : 'false' , " ?\n"; # false print "false is " , is_ci(\"nonsense") ? 'true' : 'false' , " ?\n"; # + die!
HTH

Update: Ah trustworthy guts ;-) See ikegamis response below...

Reading this thread, I second what ww questions here - if one needs to check regexp modifiers a posteriori, that seems to be an indicator for a design problem. But maybe the regexp comes from user input... ?

Replies are listed 'Best First'.
Re^2: Get regexp modifiers
by ikegami (Patriarch) on Jan 06, 2010 at 02:15 UTC

    I think ref($check_re) ne 'Regexp' can fail in modern Perls. You want to use

    use re qw( is_regexp ); is_regexp($check_re)
    Or if you want to support Perl < 5.10,
    BEGIN { eval 'use re qw( is_regexp )'; if (!defined(&is_regexp)) { my $re_class = ref qr//; *is_regexp = sub($) { local *__ANON__ = 'is_regexp'; return UNIVERSAL::isa($_[0], $re_class); }; } } is_regexp($check_re)

    That said, I don't think you should be checking if it's a compiled regex pattern at all. Just checking if it looks like one (as I did) is much more tolerant.

      I think ref($check_re) ne 'Regexp' can fail in modern Perls.

      Could you explain that? (Or post a link to the relevant documentation?)

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
        ./perl -Ilib -le' my $r = ${ qr/abc/ }; print $r; print ref($r) ?1:0; print re::is_regexp($r) ?1:0; print "abc" =~ $r ?1:0; ' (?-xism:abc) 0 1 1

        "sufficiently modern" appears to mean ≥5.12 in this case