References in PERL - BunksAllowed

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

Community

demo-image

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.

1
2
3
4
5
6
7
$sref = \$foo;
$aref = \@ARGV;
$href = \%ENV;
$cref = \&handler;
$gref = \*foo;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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


1
2
3
4
5
6
$href = {
'India' => 'Delhi',
'USA' => 'New York',
};
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.


1
2
3
4
5
6
7
8
9
10
#!/usr/bin/perl
$var = 15;
$r = \$var;
print "$var is : ", $$r, "\n";
@var = (10, 20, 30);
$r = \@var;
print "@var is : ", @$r, "\n";
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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


1
2
3
4
5
6
7
8
9
10
#!/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";
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Circular References

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


1
2
3
4
5
6
7
8
#!/usr/bin/perl
my $var = 10;
$var = \$var;
print "", $$var, "\n";
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.


1
2
3
4
5
6
7
8
9
10
#!/usr/bin/perl
sub Print1 {
my (%hash) = @_;
foreach $item (%hash) {
print "Item : $item\n";
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX




Happy Exploring!

Comment Using!!

No comments:

Post a Comment

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