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.

In reply to Re^6: simple array question by Marshall
in thread simple array question by tw

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.