PERL TUTORIALS - Perl References
Perl References
ADVERTISEMENTS
Create References:
$scalarref = \$foo; $arrayref = \@ARGV; $hashref = \%ENV; $coderef = \&handler; $globref = \*foo;ADVERTISEMENTS
$arrayref = [1, 2, ['a', 'b', 'c']];ADVERTISEMENTS
$hashref = { 'Adam' => 'Eve', 'Clyde' => 'Bonnie', };
$coderef = sub { print "Boink!\n" };Dereferencing:
#!/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";
#!/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";Circular References
#!/usr/bin/perl my $foo = 100; $foo = \$foo; print "Value of foo is : ", $$foo, "\n";References to Functions
#!/usr/bin/perl # Function definition sub PrintHash{ my (%hash) = @_; foreach $item (%hash){ print "Item : $item\n"; } } %hash = ('name' => 'Tom', 'age' => 19); # Create a reference to above function. $cref = \&PrintHash; # Function call using reference. &$cref(%hash);