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


in reply to Re^3: Tokenizing and qr// <=> /g interplay
in thread Tokenizing and qr// <=> /g interplay

When Perl sees a regex comprised solely of a single variable, Perl checks to see if that variable is a Regexp object (what qr// returns). If it is, Perl knows that the regex has already been compiled, so it simply uses the compiled regex in the place of the regex.

Really? That is very interesting. So if I have:

my $true = qr/y(?:es|up)?|1|enabled?/i; my $false = qr/n(?:o(?:pe)?)?|0|disabled?/i; die "Need boolean input" unless /^(?:$true|$false)$/; if (/$true/) { do_stuff(); }
you're saying that in the die's unless clause, it will need to completely recompile the regex? That is not my interpretation, but I could be completely wrong here.

My assumption is that both $true and $false are compiled once, and only once, and the unless modifier above would not need to recompile either one.

Even if that is the case, I use code like the above because I like to be able to reuse a common criteria for truth and falseness across many expressions - sometimes, as in the die statement above, for validation that the value is something (i.e., not a typo - if someone had "y]", we'd not accidentally treat that as a false value, we'd simply reject it so the user could fix the typo), or, at other times, such as the if statement above, just to see which one it was. Which goes to the OP's question on why it's useful, somewhat in agreement with other posts here. I'm just showing a concrete example of real, live, production code where I use this construct.