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"

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 ""

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