in reply to Can Schwartzian transform be modified to sort an arrayref uniquely?
Well, before we get to your question, there are a few things that need to be cleared up. First, it's good to see you trying out advanced techniques and getting more tools in your box, but you do have a few issues.
Your first data structure has parentheses around it. That makes it a comma expression which, when evaluated in list context, will return a list. In scalar context, its value is whatever the last item evaluates to. You only have one item, so your scalar gets the array ref and your code works, but you should avoid doing things like this unless you're positive that this is what you need. Drop the parentheses.
The Schwartzian is overkill. A Schwartzian transform is great if you have an expensive step to extract the data and put it in a sortable format. You do not have such a step. Your Schwartzian reduces to this:
my @sorted = sort { $a->{num} cmp $b->{ num } } @$data;
If it makes you feel better, I was caught by the same issue. See Sort on Boredom :)
Here's how I shortened your code:
#!/usr/local/bin/perl -w use strict; my $data = [ { num => 'OF1234', title => 'title OF1234', }, { num => 'AF1234', title => 'title AF1234', }, { num => 'AF1234', title => 'title AF1234', }, ]; my %saw; my @sorted = grep { ! $saw{$_->{num}}++ } sort { $a->{num} cmp $b->{ num } } @$data; print join ', ', map { $_->{num} } @sorted;
Hope that helps.
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(tye)Re: Can Schwartzian transform be modified to sort an arrayref uniquely?
by tye (Sage) on Jan 04, 2002 at 22:13 UTC | |
by khkramer (Scribe) on Jan 04, 2002 at 22:51 UTC | |
|
Re: (Ovid) Re: Can Schwartzian transform be modified to sort an arrayref uniquely?
by gbarr (Monk) on Jan 05, 2002 at 01:24 UTC |