friedo
friedo

Reputation: 67048

What's the deal with reftype { }?

I recently saw some code that reminded me to ask this question. Lately, I've been seeing a lot of this:

use Scalar::Util 'reftype';

if ( reftype $some_ref eq reftype { } ) { ... }

What is the purpose of calling reftype on an anonymous hashref? Why not just say eq 'HASH' ?

Upvotes: 7

Views: 1122

Answers (1)

Robert P
Robert P

Reputation: 15978

You could compare it to 'HASH' now, because that's what comes back now.

But it might not always.

A good example is the change they did to a compiled regex. In older Perls reftype was a SCALAR. However, as of 5.12 (I believe) it is now its own type, REGEXP. Example:

perl -MScalar::Util=reftype -e "print reftype qr//" on 5.8 gives SCALAR, but the same on 5.12 gives REGEXP.

You can see another application of this from this question I asked a while back, except there it used ref instead of reftype. Principle is the same though.

Simply, by comparing it to reftype {}, they're guarenteeing that it's exactly right now and in the future without (and I think this is the killer feature) hardcoding yet another string into your program.

Upvotes: 6

Related Questions