A Perl reference is a scalar data type that holds the location of another value which could be scalar, arrays, or hashes.
A list can be constructed having references to other lists.
Create References
To create a reference for a variable, subroutine or value, a backslash is added before the variable name as follows.
But remember that a reference can not be created on an I/O handle
(filehandle or dirhandle), though a reference can be created for an
anonymous array as
$arrayref = [10, 20, ['x', 'y', 'z']];
.
Similarly, a reference to an anonymous hash can be created using the curly brackets as
A reference to an anonymous subroutine can also be created as
$cref = sub { print "Hello!\n" };
Dereferencing
We can use $, @ or % as prefix of the reference variable to dereference it. Let's try the following code.
If data type of the variables are unknown, we can check the type. Let's try the following example
Circular References
Let's try the following code. But be very careful as a circular reference can lead to memory leaks.
References to Subroutines
A reference to a subroutine can be created by adding \& before subroutine name. Similarly, dereferencing can be performed by placing & before subroutine name as shown below.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.