Comparing reference types in Perl

A beginner-level tip concerning the ref function.


Are you a Perl programmer? Maybe just maintaining somebody else's code? Do you write your reference type conditions like this?

if (ref $probably_hash eq "HASH") { ... }

This is correct but looks ugly and gives you more room for error. You probably need to consult manual from time to time for the exact spelling and even then there's a chance you'll get it wrong and your checks will always fail silently at runtime.

No need to worry! There's a smoother although not an obvious way of saying what you mean.

if (ref $probably_hash eq ref {}) { ... }

This is idiomatic way of getting the correct string without much room for error. If you make a mistake it will error out at compile time which is much better than what you get when typing the word manually. Here's the table of related expressions I consider useful.

say ref \0;    # returns "SCALAR"
say ref {};    # returns "HASH"
say ref [];    # returns "ARRAY"
say ref sub{}; # returns "CODE"

Keep in mind having this instead of a string will cause your program to run a bit slower. Perl compiler will not inline this for you, it will create a reference and take its type every time it is run.

On a side note: If you just want to know if the scalar is a reference you can simply type !ref $scalar instead of ref $scalar eq "" (unless you have a package named , that is).

Also consider using core Scalar::Util module for it's reftype() and blessed() functions to avoid ambiguity when necessary.


Comments? Suggestions? Send to bbrtj.pro@gmail.com
Published on 2019-07-27