One very powerful operation in Perl is the "list slice". The code
below shows a general application of that concept. With a list
slice, you can say: "I want the first element of an array, the
last element of an array, and the the second element of an array",
and assign those things to variables on the left hand side of the
equals sign. WOW!
Here, [ 0,-1,1 ] look like indicies, but they aren't really
the same thing. For example, [ -1 ], what kind of index is that?
None. That -1 means the last thing in the list.
I am currently working with a database output that has hundreds
of things on a line. I can assign the 89th thing, the 21st thing
to Perl variables. my ($name,$address) = (@stuff)[ 88, 20 ]. The other things don't matter and I don't have to assign say, $zip_code to something that I am not going to use later in the code.
#!/usr/bin/perl -w
use strict;
my @compass =
(
["NW", "N", "X", "NE"],
["W", "center", "X", "E"],
["SW", "S", "X","SE"],
);
foreach my $compass_row (@compass)
{
my ($first, $last, $second) = (@$compass_row)[0,-1,1];
my ($only_first) = (@$compass_row)[0];
print "only the first thing: $only_first\n";
print " first=$first last=$last second=$second\n";
}
__END__
Prints:
only the first thing: NW
first=NW last=NE second=N
only the first thing: W
first=W last=E second=center
only the first thing: SW
first=SW last=SE second=S
Oh, of course $first and $only_first are the same. I assigned different variables to emphasize that there is no connection between the first and second list slice statements. |