Perl Module Basics
This example works similarly to the earlier example and uses an @ to deference
the reference to @array. This works fine for access to the whole array, but more
often you'll want to pick out a single value:
print $ref >[0] . "\n"; # prints "Hello,"
This syntax is known as arrow notation. You can use arrow notation with hashes
as well. For example, here's another way to print Hello, New World , this time
using a reference to a hash:
%hash = ( message => "Hello, New World" );
$ref = \%hash;
print $ref >{message} . "\n";
Finally, Perl contains operators to create array and hash references without
requiring an intermediate variable. These are known as anonymous arrays and
anonymous hashes, respectively. For example, the preceding example could be
rewritten to use an anonymous hash:
$ref = { message => "Hello, New World" };
print $ref >{message} . "\n";
The curly braces ({}) produce a reference to an anonymous hash. Similarly,
square braces ([]) produce a reference to an anonymous array:
$ref = [ "Hello", "New", "World" ];
print join(" ", @$ref) . "\n";
References are often used to implement call by reference in subroutines. Call
by reference means that the subroutine takes a reference as a parameter and acts
on the data pointed to by the reference. For example, here's a function that takes
a reference to an array of words and uppercases them:
sub upper {
my $words = shift;
$words >[$_] = uc($words >[$_]) for (0 .. $#$words);
}
Notice that this subroutine doesn't return anything it works by modifying the
array pointed to by the reference passed as the first parameter. Here's an example
of how upper() would be used:
my @words = ("Hello,", "New", "World");
upper(\@words);
print join(" ", @words) . "\n"; # prints "HELLO, NEW WORLD"
...........................................................................................................................................................................................................................
37
37
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved