Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Dereferencing in Perl
Dereferencing in Perl returns the value from a reference point to the location. To dereference a reference simply use $, @ or % as a prefix of the reference variable depending on whether the reference is pointing to a scalar, array, or hash. Following is the example to explain the concept −
Example
#!/usr/bin/perl
$var = 10;
# Now $r has reference to $var scalar.
$r = \$var;
# Print value available at the location stored in $r.
print "Value of $var is : ", $$r, "\n";
@var = (1, 2, 3);
# Now $r has reference to @var array.
$r = \@var;
# Print values available at the location stored in $r.
print "Value of @var is : ", @$r, "\n";
%var = ('key1' => 10, 'key2' => 20);
# Now $r has reference to %var hash.
$r = \%var;
# Print values available at the location stored in $r.
print "Value of %var is : ", %$r, "\n";
Output
When the above program is executed, it produces the following result −
Value of 10 is : 10 Value of 1 2 3 is : 123 Value of %var is : key220key110
If you are not sure about a variable type, then it's easy to know its type using ref, which returns one of the following strings if its argument is a reference. Otherwise, it returns false −
SCALAR ARRAY HASH CODE GLOB REF
Example
Let's try the following example −
#!/usr/bin/perl
$var = 10;
$r = \$var;
print "Reference type in r : ", ref($r), "\n";
@var = (1, 2, 3);
$r = \@var;
print "Reference type in r : ", ref($r), "\n";
%var = ('key1' => 10, 'key2' => 20);
$r = \%var;
print "Reference type in r : ", ref($r), "\n";
Output
When the above program is executed, it produces the following result −
Reference type in r : SCALAR Reference type in r : ARRAY Reference type in r : HASH
Advertisements
