corporate_gadfly has asked for the wisdom of the Perl Monks concerning the following question:
My code looks like this (I'm trying to sort uniquely on the field called num):
which produces the desired output (first line sorted, second line unique):#!/usr/local/bin/perl -w use strict; my $data = ( [ { num => 'OF1234', title => 'title OF1234', }, { num => 'AF1234', title => 'title AF1234', }, { num => 'AF1234', title => 'title AF1234', }, ] ); #print @{$data}; my @sorted = # now get the original array ref back map { $_->[0] } # use field 1 of anonymous array to sort (in this # case num) sort { $a->[1] cmp $b->[1] } # make an anonymous array of itself and num map { [$_, $_->{num}] } # start with the array ref and make it an array @{$data}; print join ', ', map { $_->{num} } @sorted; print "\n"; my %saw; undef %saw; my @unique = grep !$saw{$_->{num}}++, @sorted; print join ', ', map { $_->{num} } @unique; print "\n"; exit;
Is there a way to get rid of the unsightly grep by using something similar to:AF1234, AF1234, OF1234 AF1234, OF1234
keeping in mind that we're talking about hash data inside the arrrayref.my @keys = sort keys %{ { map { $_ => 1 } @array1 } };
I can't get my hands around it. It's a wonder that I understand the Schwartzian Transform to begin with. Here's a detailed explanation of the Schwartzian at http://www.5sigma.com/perl/schwtr.html for people wanting to know more. Thanks in advance,
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(Ovid) Re: Can Schwartzian transform be modified to sort an arrayref uniquely?
by Ovid (Cardinal) on Jan 04, 2002 at 21:54 UTC | |
by tye (Sage) on Jan 04, 2002 at 22:13 UTC | |
by khkramer (Scribe) on Jan 04, 2002 at 22:51 UTC | |
by gbarr (Monk) on Jan 05, 2002 at 01:24 UTC | |
|
Re: Can Schwartzian transform be modified to sort an arrayref uniquely?
by khkramer (Scribe) on Jan 04, 2002 at 21:57 UTC | |
|
Re: Can Schwartzian transform be modified to sort an arrayref uniquely?
by petral (Curate) on Jan 04, 2002 at 22:36 UTC |