tags:

views:

82

answers:

1

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

+5  A: 

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.

Robert P
Makes perfect sense, thanks. Maybe I will revisit some old code and add some Readonly constants, e.g. `$HASH_TYPE = reftype { };`
friedo
In case it changes to ASSOCIATIVE_ARRAY at some point? Don't bother. It's not changing.
ysth
Are you sure it's not going to change in Perl 6, which is supposed to have a Perl 5 mode? Also things like 1, 0, 42, and other magic values aren't going to change either. It still doesn't mean we should hardcode them, make possible typos the compiler can't catch, etc.
brian d foy
I think that's the biggest feature - you can't miss type it. `ARAAY` and `AARRY` and `ARRAY` all look very similar at a glance. Testing would unveil the problem, but testing for a problem is merely a cure for the disease. If you can avoid becoming infected by doing something so obviously right that it can't possibly be wrong, you avoid the problem entirely.
Robert P