From ref() to reftype()

I knew this day was coming.

Today I'm changing a bunch of code which uses ref() (specifically, code which checks whether something is a coderef: ref($foo) eq 'CODE') to use reftype() instead. reftype() works with blessed coderefs. And I will be encountering blessed coderefs quite a bit since my function wrapper (Perinci::Sub::Wrapper) marks its generated wrapper code by blessing them. I'm not even sure how that would be useful, but I'd still like to know if some function has been wrapped.

I have been putting off this for months (more than a year?) simply because I'm lazy. Personal technical debt, you may say.

Come to think of it: Having to use Scalar::Util, List::Util, List::MoreUtils, etc for seemingly basic functions is a sign of Perl's age, but also a sign of how serious Perl is when it comes to backwards compatibility. We aren't that bad too, remember that poor Python users need to be this verbose when it comes to basic stuffs, like from os import getenv; home = getenv('HOME').

EDIT: Damn you, Murphy's Law. Turns out ref() has one nicety reftype() lacks:

ref(undef); # ''
reftype(undef); # undef

Because I took advantage of this, now I have to clean a bunch of undef warnings due to the change to reftype() (yes, basically have to, due to Moo/strictures).


Although reftype() supports blessed coderefs, it sadly doesn't support blessed non-coderefs that overload "&{}".

Perl really needs its does built-in.

If you need really pedantic type checking, check out Params::Util, and in the case of coderef and things that can be called as a coderef, check out the _CODELIKE function. (yes, it exports functions with all-caps and it's ugly but hey, it works and the function names do describe what they do)

Leave a comment

About Steven Haryanto

user-pic A programmer (mostly Perl 5 nowadays). My CPAN ID: SHARYANTO. I'm sedusedan on perlmonks. My twitter is stevenharyanto (but I don't tweet much). Follow me on github: sharyanto.