Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the deal with reftype { }?

Tags:

perl

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' ?

like image 728
friedo Avatar asked May 25 '10 21:05

friedo


1 Answers

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.

like image 94
Robert P Avatar answered Sep 28 '22 17:09

Robert P