beable has asked for the wisdom of the Perl Monks concerning the following question:
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__
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: So what is an array slice anyway?
by blokhead (Monsignor) on Aug 26, 2004 at 01:38 UTC | |
by revdiablo (Prior) on Aug 26, 2004 at 05:37 UTC | |
by beable (Friar) on Aug 26, 2004 at 04:42 UTC | |
by revdiablo (Prior) on Aug 26, 2004 at 05:49 UTC | |
Re: So what is an array slice anyway?
by antirice (Priest) on Aug 26, 2004 at 03:25 UTC | |
by beable (Friar) on Aug 26, 2004 at 04:52 UTC | |
by Aristotle (Chancellor) on Aug 26, 2004 at 08:13 UTC | |
by beable (Friar) on Aug 26, 2004 at 07:20 UTC | |
by McMahon (Chaplain) on Aug 26, 2004 at 14:29 UTC |
Back to
Seekers of Perl Wisdom