You are viewing the version of this documentation from Perl blead. This is a development version of Perl.
ref EXPR
ref

Examines the value of EXPR, expecting it to be a reference, and returns a string giving information about the reference and the type of referent. If EXPR is not specified, $_ will be used.

If the operand is not a reference, then the empty string will be returned. An empty string will only be returned in this situation. ref is often useful to just test whether a value is a reference, which can be done by comparing the result to the empty string. It is a common mistake to use the result of ref directly as a truth value: this goes wrong because 0 (which is false) can be returned for a reference.

If the operand is a reference to a blessed object, then the name of the class into which the referent is blessed will be returned. ref doesn't care what the physical type of the referent is; blessing takes precedence over such concerns. Beware that exact comparison of ref results against a class name doesn't perform a class membership test: a class's members also include objects blessed into subclasses, for which ref will return the name of the subclass. Also beware that class names can clash with the built-in type names (described below). Use the isa method to test class membership of a class name or blessed object, after ensuring it is one of these things. Alternatively, the isa operator can test class membership without checking blessedness first.

If the operand is a reference to an unblessed object, then the return value indicates the type of object. If the unblessed referent is not a scalar, then the return value will be one of the strings ARRAY, HASH, CODE, FORMAT, or IO, indicating only which kind of object it is. If the unblessed referent is a scalar, then the return value will be one of the strings SCALAR, VSTRING, REF, GLOB, LVALUE, or REGEXP, depending on the kind of value the scalar currently has. But note that qr// scalars are created already blessed, so ref qr/.../ will likely return Regexp. Beware that these built-in type names can also be used as class names, so ref returning one of these names doesn't unambiguously indicate that the referent is of the kind to which the name refers.

The ambiguity between built-in type names and class names may limit the utility of ref, but in practice, such clashes rarely occur unless intentionally engineered. For unambiguous information, use "blessed" in builtin for information about blessing, and "reftype" in builtin for information about physical types. But beware that the physical type returned by reftype does not indicate how a blessed object is meant to be used, and the appropriate dereference operations for an object (whether to access the blessed structure directly, or via an overload) will be described by the documentation for the object class.

See also perlref and perlobj.