References in PERL - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

References in PERL

Share This

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.

$sref = \$foo; $aref = \@ARGV; $href = \%ENV; $cref = \&handler; $gref = \*foo;

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


$href = { 'India' => 'Delhi', 'USA' => 'New York', };

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.


#!/usr/bin/perl $var = 15; $r = \$var; print "$var is : ", $$r, "\n"; @var = (10, 20, 30); $r = \@var; print "@var is : ", @$r, "\n"; %var = ('key1' => 100, 'key2' => 200); $r = \%var; print "%var is : ", %$r, "\n";

If data type of the variables are unknown, we can check the type. Let's try the following example


#!/usr/bin/perl $var = 15; $r = \$var; print "Type of r is : ", ref($r), "\n"; @var = (10, 20, 30); $r = \@var; print "Type of r is : ", ref($r), "\n"; %var = ('key1' => 10, 'key2' => 20); $r = \%var; print "Type of r is : ", ref($r), "\n";

Circular References

Let's try the following code. But be very careful as a circular reference can lead to memory leaks.


#!/usr/bin/perl my $var = 10; $var = \$var; print "", $$var, "\n";

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.


#!/usr/bin/perl sub Print1 { my (%hash) = @_; foreach $item (%hash) { print "Item : $item\n"; } } %hash = ('name' => 'Titli', 'age' => 1); $cref = \&Print1; &$cref(%hash);




Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.