| Previous | Next
References and Complex Data StructuresA Perl reference is a fundamental data type that "points" to another piece of data or code. A reference knows the location of the information and the type of data stored there. A reference is a scalar and can be used anywhere a scalar can be used. Any array element or hash value can contain a reference (a hash key cannot contain a reference), which is how nested data structures are built in Perl. You can construct lists containing references to other lists, which can contain references to hashes, and so on. Creating ReferencesYou can create a reference to an existing variable or subroutine by prefixing it with a backslash:
References to scalar constants are created similarly: $pi = \3.14159; $myname = \"Charlie"; Note that all references are prefixed by a $aref = \@names; $bref = $aref; # Both refer to @names $cref = \$aref; # $cref is a reference to $aref Because arrays and hashes are collections of scalars, you can create references to individual elements by prefixing their names with backslashes:
Referencing anonymous dataIt is also possible to take references to literal data not stored in a variable. This data is called anonymous because it is not bound to any named variable. To create a reference to a scalar constant, simply backslash the literal string or number. To create a reference to an anonymous array, place the list of values in square brackets: $shortbread = [ "flour", "butter", "eggs", "sugar" ]; This creates a reference to an array, but the array is available only through the reference A reference to an anonymous hash uses braces around the list of elements:
DereferencingDereferencing returns the value a reference points to. The general method of dereferencing uses the reference variable substituted for the regular name part of a variable. If When a reference is accidentally evaluated as a plain scalar, it returns a string that indicates the type of data it points to and the memory address of the data. If you just want to know the type of data that is being referenced, use SCALAR ARRAY HASH CODE GLOB REF Arrow dereferencingReferences to arrays, hashes, and subroutines can be dereferenced using the
The first statement dereferences The arrow dereferencing notation can be used only to access a single scalar value. You cannot use arrow operators in expressions that return either slices or whole arrays or hashes. |