http://qs321.pair.com?node_id=618533

kyle has asked for the wisdom of the Perl Monks concerning the following question:

In Object Oriented Perl, Chapter 5, TheDamian blesses a regular expression made with qr (see perlop). I never gave much thought to this, but I recently noticed the following:

What this seems to mean is that once I bless a regular expression into some other class, I can't tell that it's really a regular expression under the hood anymore, but it is. I also can't tell if some scalar reference is really a regexp or just some scalar that some joker decided to call a 'Regexp'.

The code below demonstrates what I'm talking about. In it, a real regular expression is examined and used both before and after being blessed. Next, a blessed scalar ref is examined the same way. It looks the same, but it doesn't work the same.

use Test::More 'tests' => 25; use Scalar::Util qw( reftype blessed ); ok( 'foo' =~ //, '"foo" matches empty expression' ); # a real regexp, not blessed, works like this my $rx = qr/f(oo)/; is( ref $rx, 'Regexp', 'ref $rx eq "Regexp"' ); is( blessed $rx, 'Regexp', '$rx is blessed as "Regexp"' ); is( reftype $rx, 'SCALAR', 'reftype $rx eq "SCALAR"' ); ok( ! defined $$rx, '$$rx is not defined' ); ok( 'foo' =~ $rx, '$rx matches "foo"' ); is( $&, 'foo', 'matched text is "foo"' ); is( $1, 'oo', 'first capture is "oo"' ); # a blessed regexp works the same way, # but what other evidence can tell me it's a regexp? bless $rx, 'NotRegexp'; is( ref $rx, 'NotRegexp', 'ref $rx eq "NotRegexp"' ); is( blessed $rx, 'NotRegexp', '$rx is blessed as "NotRegexp"' ); is( reftype $rx, 'SCALAR', 'reftype $rx eq "SCALAR"' ); ok( ! defined $$rx, '$$rx is not defined' ); ok( 'foo' =~ $rx, '$rx matches "foo"' ); is( $&, 'foo', 'matched text is "foo"' ); is( $1, 'oo', 'first capture is "oo"' ); # this looks just like the blessed regexp, but it doesn't function my $o; my $notrx = \$o; bless $notrx, 'NotRegexp'; is( ref $notrx, 'NotRegexp', 'ref $notrx eq "NotRegexp"' ); is( blessed $notrx, 'NotRegexp', '$notrx is blessed as "NotRegexp"' ); is( reftype $notrx, 'SCALAR', 'reftype $notrx eq "SCALAR"' ); ok( ! defined $$notrx, '$$notrx is not defined' ); ok( !('foo' =~ $notrx), '$notrx does not match "foo"' ); # this looks just like the real regexp, but it doesn't function bless $notrx, 'Regexp'; is( ref $notrx, 'Regexp', 'ref $notrx eq "Regexp"' ); is( blessed $notrx, 'Regexp', '$notrx is blessed as "Regexp"' ); is( reftype $notrx, 'SCALAR', 'reftype $notrx eq "SCALAR"' ); ok( ! defined $$notrx, '$$notrx is not defined' ); ok( !('foo' =~ $notrx), '$notrx does not match "foo"' );

My question is, how can I tell if some scalar reference I receive really is a regular expression? Obviously, if it produces a match when used, I know it is a regular expression (a scalar reference to a string won't act as a regexp), but a non-match doesn't tell me much.