You've known Perl for 15 minutes? Forget about references for now.
Basically, everything passed to a subroutine is an array. In fact, it's stored in an array called @_
.
# /usr/bin/env perl
use strict; #ALWAYS USE!
use warnings; #ALWAYS USE!
my @array = qw(member1 member2 member3 member4);
foo(@array, 'scalar', 'scalar', 'scalar');
sub foo {
print "My input is " . join (":", @_) . "\n";
This will print:
my input is member1:member2:member3:member4:scalar:scalar:scalar
There is no way to tell which entries are from an array and which are from a scalar. As far as your subroutine is concerned, they're all members of the array @_
.
By the way, Perl comes with a command called perldoc
. When someone says to see perlref
, you can type in perldoc perlref
at the command line and see the documentation. You can also go to the site http://perldoc.perl.org
which will also contain the same information found in the perldoc
command.
Now about references....
A data element of a Perl array or the value of a hash can only contain a single value. That could be a string, it could be a real number, it could be an integer, and it could be a reference to another Perl data structure. That's where all the fun and money is.
For example, the same subroutine foo
above could have taken this information:
foo(\@array, 'scalar', 'scalar', 'scalar'); #Note the backslash!
In this case, you're not passing in the values of @array
into foo
. Instead, a reference to the array is passed as the first data element of @_
. If you attempted to print out $_[0]
, you'd get something like ARRAY:6E43832
which says the data element is an array and where it's located in memory.
Now, you can use the ref
function to see whether an piece of data is a reference and the type of reference it is:
sub foo {
foreach my $item (@_) {
if (ref $item eq 'ARRAY') {
print "This element is a reference to an array\n";
}
elsif (ref $item eq 'HASH') {
print "This element is a reference to a hash\n";
}
elsif (ref $item) { #Mysterious Moe Reference
print "This element is a reference to a " . lc (ref $item) . "\n";
}
else {
print "This element is a scalar and it's value is '$item'\n";
}
}
}
Of course, your reference to an array might be an array that contains references to hashes that contain references to arrays and so on. There's a module that comes with Perl called Data::Dumper
(you can use perldoc
to see information about it) that will print out the entire data structure.
This is how object orient Perl works, so it's really quite common to have references to other Perl data structures embedded in a piece of Perl data.
Right now, just get use to basic Perl and how it works. Then, start looking at the various tutorials about Perl references in Perldoc.