Re: compare two sorted array, item by item, which one is bigger
Rainer Weikusat <[email protected]> Wed, 28 Feb 2024 16:34:35 +0000
| Newsgroups | comp.lang.perl.misc |
|---|---|
| Message-ID | <[email protected]> |
hymie! <[email protected]> writes: > In our last episode, the evil Dr. Lacto had captured our hero, > Rainer Weikusat <[email protected]>, who said: >> hymie! <[email protected]> writes: >>> The question is -- how can I (or can I) programatically keep checking >>> entries in the arrays of the %scores hash until I find a pair of >>> entries that are not equal? >> >> If your arrays are always of equal length, you could use > > I don't think I can depend on that :( > >> otherwise, it's a bit more difficult. >> >> sub ary_cmp >> { >> my ($a0, $a1) = @_; >> my ($last, $rc); >> >> # we need the length of the shorter array >> # start with the length of array a0 >> # and see if the length of array a1 is less >> $last = $#$a0; >> $_ < $last and $last = $_ for $#$a1; >> >> # for each entry in the shorter array >> # compare that numbered entry in the two arrays >> # return <=> if the result is not 0 >> for (0 .. $last) { >> $_ and return $_ for $$a0[$_] <=> $$a1[$_]; >> } >> >> # all of the elements are equal, so return the longer array >> return @$a0 <=> @$a1; >> } > > I took the liberty of adding your improvement to this function. > > I'll definitely try this out and see how well it work. > > I have a few followup questions... > > (*) I added some comments. Can you tell me if I'm correct? Yes. > > (*) Could I have set $last this way? > > $last = $#$a0 < $#$a1 ? $#$a0 : $#$a1 ; > > or > > $last = @$a0 < @$a1 ? @$a0 : @$a1 ; The first yes, second no as $#$a0 == @$a0 - 1. It's just syntactically a bit more repetitive. > > ? > > (*) In this construct > >> for (0 .. $last) { >> $_ and return $_ for $$a0[$_] <=> $$a1[$_]; > > is it safe to reuse $_ like that? Yes. The foreach-for aliases a localized $_ to the first element and then executes the loop body, ie, either the block in case of for (...) { } or the statement for the statement modifier. Then, it does the same with the second element and so forth, until the body has been run for all list elements. This means $_ reverts back to the current index after the $_ and return $_ has been executed.