Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re^3: So what is an array slice anyway?

by beable (Friar)
on Aug 26, 2004 at 07:20 UTC ( #385927=note: print w/replies, xml ) Need Help??

in reply to Re^2: So what is an array slice anyway?
in thread So what is an array slice anyway?

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.
#!/usr/bin/perl use strict; use warnings; my @arr1 = (1, 2, 3, 4); my @arr2 = (4 .. 7); # from "perldoc perldata": # # If you evaluate an array in scalar context, it returns the length of # the array. (Note that this is not true of lists, which return the # last value, like the C comma operator) # note that an array slice is a list, not an array # see perldoc -q "difference between a list and an array" print "-" x 72, "\nbroken wrong way to do it:\n"; if (@arr1 == @arr2) { print "\@arr1 same length as \@arr2\n"; } if (@arr1[2,3] == @arr2[4,2,0]) { print "the two slice expressions each have the same number on the" +, " end of the list\n"; } if ((1,3,9) == (-10000,34,52,42,9)) { print "those two lists end with the same number\n"; } my @arr3 = @arr1[2,3]; my @arr4 = @arr2[4,2,0]; if (@arr3 != @arr4) { print "\@arr3 different length from \@arr4\n"; } print "-" x 72, "\na correct way to see if arrays are equal:\n"; print "two arrays\n"; if (! arr_comp(\@arr1, \@arr2)) { print "\@arr1 is not equal to \@arr2\n"; } # need to turn slices into arrays to compare them # see "perldoc -f scalar" print "two slices\n"; if (! arr_comp(\@{[ @arr1[2,3] ]}, \@{[ @arr2[3,2,0] ]})) { print "the two slices are not equal\n"; } print "two more slices\n"; if (arr_comp(\@{[ @arr3[0,1] ]}, \@{[ @arr1[2,3] ]})) { print "these two slices are equal\n"; } # compares two arrays, returns true if they are the same, false # if they aren't # pass in references to the arrays, please sub arr_comp { my $arr1 = shift; my $arr2 = shift; print "comparing @$arr1 and @$arr2\n"; my $same = 0; if (@$arr1 != @$arr2) { # arrays have different length return $same; } $same = 1; for (my $i = 0; $i <= $#$arr1; $i++) { # using ne so it works for strings too if ($arr1->[$i] ne $arr2->[$i]) { $same = 0; last; } } return $same; } __END__

Thanks for your help.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://385927]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2023-03-27 11:06 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (65 votes). Check out past polls.