http://qs321.pair.com?node_id=385896


in reply to So what is an array slice anyway?

Behold!

my @p = (0..10); my @q = (1..9); if ( ( () = @p[0,1,2] ) == ( () = @q[3,6,1] ) ) { print "p slice == q slice\n" }

You can either assign your slice directly to an array and compare the scalar value of the arrays or you can use ( () = LIST ) and compare them directly.

Disclaimer: I also like Lisp, so I see some beauty in the parentheses bomb.

antirice    
The first rule of Perl club is - use Perl
The
ith rule of Perl club is - follow rule i - 1 for i > 1

Replies are listed 'Best First'.
Re^2: So what is an array slice anyway?
by beable (Friar) on Aug 26, 2004 at 04:52 UTC
    That's an interesting thing to be doing. However, I think the person who asked me the question is actually trying to find out whether arrays and array slices are "equal" by using the "==" operator. I tried to explain how it was comparing the number of elements in arrays by using scalar context, but he suddenly went to bed. I was hoping there would be a function in List::Util to compare arrays and return if they are equal, but no luck there. Sorry for not making that clear before. What he wants to do is to 1) compare arrays to see if they have all the same elements in, and 2) compare array slices to see if they have all the same elements in. I think he should just write a subroutine to do it. But I sure think he shouldn't be using "==" to do it.

      Here's an idiomatic way to test whether the contents of two arrays are equal — assuming the elements are numbers, anyway.

      print "equal\n" if @array1 == @array2 and !grep $array1[ $_ ] != $array2[ $_ ], 0 .. $#array1;

      In scalar context, grep evaluates to the number of elements it returned, so that condition says "if both arrays have the same length, and if no elements are found which are not equal".

      Makeshifts last the longest.

      Okay, here's what I'm going to give him. Hopefully it will make him think again about using == for this sort of thing. Hopefully it has enough examples and pointers to the documentation to show him what's up.

      Thanks for your help.

      I do this sort of thing a lot. List::Compare makes it pretty easy.