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__