codescracker


perl

Perl References



« Previous Tutorial Next Tutorial »


Reference in perl, is a scalar data type that is used to hold the location of another value, that might be scalar, array, or hashes.

Create Reference in Perl

Here is an example creating reference for any variable, subroutine or value simply by prefixing it with a backslash:

$scalarreference = \$foo;
$arrayreference  = \@ARGV;
$hashreference   = \%ENV;
$codereference   = \&handler;
$globreference   = \*foo;

Here is an example creating reference to an anonymous array. Reference to an anonymous array can be created using square brackets:

$arrayreference = [1, 2, 3, ['a', 'b', 'c']];

Here is another example, creating reference to an anonymous hash using the curly braces:

$hashreferencee = { 'Adam'  => 'Eve', 'Clyde' => 'Bonnie', };

Here is one more example, creating reference to an anonymous subroutine:

$codereference = sub {print("Hi\n")};

Perl Dereferencing

Dereferencing in perl, simply returns the value of that location which are pointed by the reference. To deference a reference, then use dollar ($), at (@), or percent (%) sign as prefix of the reference variable, depending on whether the reference is pointing to a array, scalar, or hash. Here is an example, demonstrates how to deference a reference in perl:

#!/usr/bin/perl

$num = 10;

# here, the $ref has reference to the $num scalar
$ref = \$num;

# this will print the value available at the location stored in the $ref
print("Value of $num = ", $$ref, "\n");

@num = (1, 2, 3);

# here, $ref has reference to the @num array
$ref = \@num;

# this will print the values available at the location stored in the $ref
print("Value of @num = ",  @$ref, "\n");

%num = ('key1' => 10, 'key2' => 20);

# here, $ref has reference to the %num hash
$ref = \%num;

# this will print the values available at the location stored in the $ref
print("Value of %num = ", %$ref, "\n");

When the above code is executed, it will produce the following output:

Value of 10 = 10
Value of 1 2 3 = 123
Value of %num = key220key110

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test