Somebody asked me a question about comparing arrays with == and comparing array slices with ==. It's not as straightforward as you might think. So what is an array slice anyway?
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @x = (2,3); my @y = (7,8); my @z = (9,8,7,6,5,4,3,2,1); # probably everybody would agree that @x == @y, because they have # the same number of elements if (@x == @y) { print "x == y\n"; } if (@x == @z) { print "x == z\n"; } if (@y == @z) { print "y == z\n"; } # But how about slices? They have the same number of elements, # right? if (@x[0,1] == @y[0,1]) { print "x slice == y slice\n"; } if (@x[0,1] == @z[0,1]) { print "x slice == z slice\n"; } if (@y[0,1] == @z[0,1]) { print "y slice == z slice\n"; } print "x array is: ", Dumper(@x), "\n"; print "y array is: ", Dumper(@y), "\n"; print "z array is: ", Dumper(@z), "\n"; print "x slice is: ", Dumper(@x[0,1]), "\n"; print "y slice is: ", Dumper(@y[0,1]), "\n"; print "z slice is: ", Dumper(@z[0,1]), "\n"; print "scalar x slice is: ", scalar(@x[0,1]), "\n"; print "scalar y slice is: ", scalar(@y[0,1]), "\n"; print "scalar z slice is: ", scalar(@z[0,1]), "\n"; # try assigning my @q = @x[0,1]; my @r = @y[0,1]; if (@q == @r) { print "q == r\n"; } # okay how about this? if (@q == @x[0,1]) { print "q == x slice\n"; } __END__

In reply to So what is an array slice anyway? by beable

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.