Classes and OO

ref#

Return a string describing what a reference points to.

ref examines its operand and returns a string identifying the kind of referent. For a blessed reference it returns the class name; for an unblessed reference it returns one of the built-in type strings (SCALAR, ARRAY, HASH, CODE, GLOB, LVALUE, IO, FORMAT, REF, VSTRING, REGEXP). For anything that is not a reference it returns the empty string. With no argument, ref operates on $_.

Synopsis#

ref EXPR
ref

What you get back#

A string. Three mutually exclusive categories:

  • Blessed reference — the name of the class the referent is blessed into. For example, a bless {}, 'Dog' reference returns "Dog". Subclasses return their own name, not the parent’s: a reference blessed into Puppy (an ISA of Dog) returns "Puppy". See bless.

  • Unblessed reference — one of the built-in type strings listed below, identifying the physical type of the referent.

  • Non-reference — the empty string "".

The empty string is the only false value ref ever returns, so if (ref $x) is a safe “is this a reference?” test. See the edge cases section for why if (ref $x eq 'HASH') is not a safe “is this a hash reference?” test.

Built-in type strings#

Returned for unblessed references according to the physical referent:

String

Referent

SCALAR

reference to an ordinary scalar

ARRAY

reference to an array

HASH

reference to a hash

CODE

reference to a subroutine

GLOB

reference to a typeglob

LVALUE

reference to an assignable expression

IO

reference to an I/O handle

FORMAT

reference to a format

REF

reference to another reference

VSTRING

reference to a v-string scalar

REGEXP

reference to a raw (unblessed) regexp

A compiled regex from qr// is blessed into the class Regexp at creation time, so ref qr/.../ normally returns "Regexp", not "REGEXP". The bare REGEXP string appears only for unblessed regex referents, which are rare outside of internals.

Examples#

Basic type probes:

ref \1              # "SCALAR"
ref []              # "ARRAY"
ref {}              # "HASH"
ref sub { }         # "CODE"
ref \*STDOUT        # "GLOB"
ref \\1             # "REF"    (reference to a reference)
ref qr/foo/         # "Regexp" (blessed)
ref "plain string"  # ""       (not a reference)
ref 42              # ""
ref undef           # ""

Blessed references return the class name:

my $obj = bless {}, 'My::Widget';
ref $obj;                       # "My::Widget"

Guard before dereferencing:

sub stringify {
    my ($v) = @_;
    return "[undef]"           if !defined $v;
    return "[ref: " . ref($v) . "]" if ref $v;
    return $v;
}

No-argument form reads $_:

for my $item (@things) {
    print "skipping non-ref\n" and next unless ref;
    ...
}

Picking the right test#

ref is the oldest introspection primitive in the language and it conflates three different questions. Modern code should pick the operator that matches the question being asked.

Is this a reference at all?

if (ref $x) { ... }             # empty string is the only false return

Is this an object of (or derived from) a given class? Use the isa operator (or the UNIVERSAL::isa method) — it walks @ISA and honours subclassing, which a literal ref comparison does not:

if ($obj isa 'My::Widget') { ... }      # true for subclasses too
if ($obj->isa('My::Widget')) { ... }    # method form

if (ref($obj) eq 'My::Widget') { ... }  # FRAGILE: fails for subclasses

What is the underlying physical type, regardless of blessing? Use Scalar::Util::reftype — it ignores the class and returns the built-in type string even for blessed references:

use Scalar::Util qw(reftype blessed);
reftype($obj);                  # "HASH" if $obj is blessed hash ref
blessed($obj);                  # class name, or undef if not blessed

Edge cases#

  • Never use ref as a truth value of the referent. A reference blessed into a class literally named 0 makes ref $obj return the string "0", which is false. This is rare by construction but the foot-gun is old and well known. Compare to the empty string instead: if (ref $x ne "").

  • Class name clashes with built-in type strings. Nothing stops you from writing package HASH; sub new { bless {}, shift }. Then ref(HASH->new) returns "HASH" — indistinguishable from an unblessed hash reference by ref alone. Use Scalar::Util::blessed to disambiguate, or reftype to ask the physical-type question directly.

  • ref on qr// returns "Regexp", not "REGEXP". qr// objects are blessed at construction; the uppercase form is only produced for the (unusual) unblessed regex reference.

  • Tied variables: ref sees through the tie to the underlying reference. Use tied to retrieve the object backing the tie.

  • Weak references are still references: ref behaves identically for weak and strong refs. Use Scalar::Util::isweak to detect weakness.

  • Overloaded stringification does not affect ref. The return value of ref is produced by the runtime, not by the object’s "" overload.

  • ref EXPR has very high precedence — it is parsed as a named unary operator. Parenthesise when the argument is anything more complex than a simple variable:

    ref $a || $b;         # parsed as (ref $a) || $b
    ref($a || $b);        # what you probably meant
    

Differences from upstream#

Fully compatible with upstream Perl 5.42.

See also#

  • bless — install a class name on a reference; the name installed here is exactly what ref returns afterwards

  • isa — class-membership test that honours @ISA inheritance; prefer this over ref(...) eq 'ClassName' for OO dispatch

  • tied — retrieve the object implementing a tied variable; ref on a tied scalar follows the tie to the referent

  • Scalar::Util::reftype — physical-type string for a reference, ignoring blessing

  • Scalar::Util::blessed — class name if blessed, undef otherwise; the unambiguous counterpart to ref for OO code

  • perlref, perlobj — reference and object model reference manuals