Wednesday, May 11, 2011

How to Check if a Variable is a Regular Expression in Perl

# 1. Using ref() on a regex reference
# $r contains a compiled regex (qr//). 
# The ref() function correctly identifies it as a 'Regexp' object.
$ perl -E "$r=qr/a/; say ref($r) eq 'Regexp' || 0"
1

# 2. Using ref() on a dereferenced regex
# Dereferencing the regex ($$r) evaluates it as a scalar string, 
# so ref() no longer sees it as a 'Regexp' object and returns 0.
$ perl -E "$r=qr/a/; say ref($$r) eq 'Regexp' || 0"
0

# 3. Using re::is_regexp() on a regex reference
# The 're' module provides a dedicated function to check for regexes,
# and correctly identifies the reference.
$ perl -E "$r=qr/a/; say re::is_regexp($r) || 0"
1

# 4. Using re::is_regexp() on a dereferenced regex
# Unlike ref(), re::is_regexp() is robust enough to detect 
# the underlying regex structure even when it has been dereferenced.
$ perl -E "$r=qr/a/; say re::is_regexp($$r) || 0"
1

No comments: