Perl Refernces
-
Upload
hayley-torres -
Category
Documents
-
view
10 -
download
0
description
Transcript of Perl Refernces
Perl Refernces
Kinds of references:
• hard: a scalar variable that points to data
• symbolic: a variable that names another reference
• typeglob: a kind of symbolic reference
$language = “english”; # a hard reference$english = “Brooklyn”; # another hard reference
print “you speak with a ${$language} accent\n”;eval “ \$$language = ‘British’;”; # another symbolic refPrint “Now you speak with a $english accent\n”;
Symbolic references are tricky:
• You can disallow symbolic references using the pragma
use strict “refs”;
Life revolves around hard references:
• A hard reference is a pointer; an address.• You can point to
– a scalar– a list or array– an associative array or hash– a subroutine
• Purpose is to allow you to create things like– array of arrays (n-dimensional arrays)– array of hashes– hash of hashes (a file hierarchy where directory == hash)
The \ Operator:
• Similar to & in C++.
• $p is a hard reference to the “a scalar” string;
• Like & in C++, you de-reference a field by using .
$x = “a scalar”;$p = \$x; # a pointer to $x
Examples:
$scalarref = \$foo;$arrayref = \@ARGV;$hashref = \%ENV;$coderef = \&handler;$globref = \*STDOUT;$reftoref = \$scalarref;
De-referencing a pointer:
• The de-reference operator is the character that precedes the variable name and indicates the data type of the variable.
$num = 5;$p = \$num;Printf ‘The address assigned to $p is ‘ . $p . “\n”;Printf “The value stored there is $$p\n”;
#outputThe address assigned to $p is SCALAR(0xb075c)The value stored there is 5
De-referencing another pointer:
@toys = qw/slinky yo-yo jack-in-the-box/;$num = @toys;$ref1 = \$num;$ref2 = \@toys;printf “There are $$ref1 toys\n”;printf “They are: @$ref2\n”;printf “My favourite toy is $ref2->[0]\n”; # could also write this as $$ref2[0]
Anonymous variables:
• Variables with no names are called anonymous.• Anonymous arrays are created with [ ]
@array = (3, 4 ,5);$arrayref = [ 3, 4, 5];@matrix = ( [1, 2, 3], [4, 5, 6], [7, 8, 9]);
printf “@matrix\n”; # prints a list of 3 addressesprintf “matrix[0,0] = $matrix[0][0]\n’; # prints matrix[0][0] = 1 # can also be written $matrix[0][0]
# print out the matrix using a loopfor ($i = 0; $i < 3; $i++) { printf “@{$matrix[0]}\n”;}
Purpose of
• The operator, called the arrow or infix operator, is used to de-reference an anonymous array or hash.
• $matrix[0] is a reference to an array de-references to get first the actual array • and then [0] gets the first element in it.
$matrix[0][0]
Anonymous hashes:
• Anonymous hashes are created with { }
$hashref = { Name => ”Woody”, Type => “Cowboy”};
printf $hashref{Name} . “\n”;printf keys(%$hashref) . “\n”;printf values(%$hashref) . “\n”;
#outputWoodyNameTypeWoodyCowboy