Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Rainer Weikusat Newsgroups: comp.lang.perl.misc Subject: Re: compare two sorted array, item by item, which one is bigger Date: Tue, 27 Feb 2024 15:37:33 +0000 Lines: 45 Message-ID: <87ttltex4y.fsf@doppelsaurus.mobileactivedefense.com> References: <87msrnyz6g.fsf@doppelsaurus.mobileactivedefense.com> Mime-Version: 1.0 Content-Type: text/plain X-Trace: individual.net 1cxkdnyJWqRfhGXDXZbwQQnTu1stsufodMu7x1Vprqpge1xXI= Cancel-Lock: sha1:/STZdbKBsVJAL/pslnF3gum0tHE= sha1:I0eb972P5W0tHxbLnT9ug5xZcw8= sha256:pqgmLlEPCgK32XN9FMcAPA4325ZvbW5fCa6YhukrgFY= User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.1 (gnu/linux) Xref: csiph.com comp.lang.perl.misc:24883 Rainer Weikusat writes: > hymie! writes: [...] >> foreach $player (sort >> {$percent{$b} <=> $percent{$a} || ${$scores{$b}}[0] <=> ${$scores{$a}}[0] } >> keys %percent) >> >> which will check the first element in each array from the %scores hash >> to see which value is larger. >> >> 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 you're arrays are always of equal length, you could use > > sub ary_cmp > { > my ($a0, $a1) = @_; > my $rc; > > for (0 .. $#$a0) { > $rc = $$a0[$_] - $$a1[$_]; > return $rc < 0 ? -1 : 1 if $rc; > } > > return 0; > } This can be simplified somewhat by using the <=> operator for the check inside the loop as that already produces the desired result of either -1, 0 or 1. sub ary_cmp { my ($a0, $a1) = @_; for (0 .. $#$a0) { $_ and return $_ for $$a0[$_] <=> $$a1[$_]; } return 0; }