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 intoPuppy(anISAofDog) returns"Puppy". Seebless.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 |
|---|---|
|
reference to an ordinary scalar |
|
reference to an array |
|
reference to a hash |
|
reference to a subroutine |
|
reference to a typeglob |
|
reference to an assignable expression |
|
reference to an I/O handle |
|
reference to a format |
|
reference to another reference |
|
reference to a v-string scalar |
|
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
refas a truth value of the referent. A reference blessed into a class literally named0makesref $objreturn 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 }. Thenref(HASH->new)returns"HASH"— indistinguishable from an unblessed hash reference byrefalone. UseScalar::Util::blessedto disambiguate, orreftypeto ask the physical-type question directly.refonqr//returns"Regexp", not"REGEXP".qr//objects are blessed at construction; the uppercase form is only produced for the (unusual) unblessed regex reference.Tied variables:
refsees through the tie to the underlying reference. Usetiedto retrieve the object backing the tie.Weak references are still references:
refbehaves identically for weak and strong refs. UseScalar::Util::isweakto detect weakness.Overloaded stringification does not affect
ref. The return value ofrefis produced by the runtime, not by the object’s""overload.ref EXPRhas 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 whatrefreturns afterwardsisa— class-membership test that honours@ISAinheritance; prefer this overref(...) eq 'ClassName'for OO dispatchtied— retrieve the object implementing a tied variable;refon a tied scalar follows the tie to the referentScalar::Util::reftype— physical-type string for a reference, ignoring blessingScalar::Util::blessed— class name if blessed,undefotherwise; the unambiguous counterpart toreffor OO codeperlref,perlobj— reference and object model reference manuals