in reply to Re^5: simple array question
in thread simple array question
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.
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.#!/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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^7: simple array question
by tw (Acolyte) on Jan 03, 2011 at 15:33 UTC | |
by Jim (Curate) on Jan 03, 2011 at 21:58 UTC | |
by tw (Acolyte) on Jan 04, 2011 at 03:04 UTC | |
by Marshall (Canon) on Jan 05, 2011 at 23:44 UTC |