[JaxPM] advanced sorting

j proctor jproctor at oit.umass.edu
Fri Jan 28 08:41:23 CST 2000


On the jacksonville-pm-list; Jax.PM'er j proctor <jproctor at oit.umass.edu> wrote -


> The names are keys in a hash, so could I do something like
> 
> @rev = reverse keys(%domainfiles);
> @sorted = reverse(sort(@rev));
> 
> and now @sorted is sorted by domain name?

Hashes don't store keys in any particular order (or, technically,
they're not guaranteed to store in any order that's easy and/or obvious
for a human to predetermine), so the first reverse probably isn't doing
much useful for you anyway.

Maybe I'm missing something, but what about leaving out the double-reverse
entirely and just using

@sorted = sort(keys(%domainfiles));

Or even build the loop into it:

foreach $domain (sort(keys(%domainfiles)))

If you're trying to sort by top-level domain first, then second-level, the
best thing to do would be to redefine sort.  Offhand, I don't remember the
exact syntax to do this, but I'd recommend your sort function (and its 
invocation) look something like:

foreach $domain (sort domainsort keys(%domainfiles))
# ... whatever you're doing with each domain ...

sub domainsort
    {
    @key1 = reverse(split('.', $a));
    @key2 = reverse(split('.', $b));    

    # determine the domain with the fewest .'s.  i thought i remembered
    # a min() function, but it wasn't mentioned in the camel.
    $min = $#key1;
    if ($min > $#key2)
        {
        $min = $#key2;
        }

    # step through the domain-parts, stop when you find a pair that
    # aren't equal, or when you reach the end of one domain-list.
    for ($i = 0; $i <= $min; $i++)
        {
        if ($key1[$i] ne $key2[$i])
            {
            last;
            }
        }

    # this is the part that i'm sorta hazy on, and should be tested:
    # return the comparison value for whatever wasn't equal, or 
    # compare the next key in a longer domain to null.
    return $key1[$i] cmp $key2[$i];
    }


Hope this helps.


j



Jax.PM Moderator's Note:
This message was posted to the Jacksonville Perl Monger's Group listserv.
The group manager can be reached at -- owner-jacksonville-pm-list at pm.org
to whom send all praises, complaints, or comments...




More information about the Jacksonville-pm mailing list