Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Twisted sort requirements

by injunjoel (Priest)
on Feb 01, 2006 at 17:58 UTC ( #527125=note: print w/ replies, xml ) Need Help??


in reply to Twisted sort requirements

Greetings all,
A little late I see but here is what I would do...

#!/usr/bin/perl -w use strict; my @things_to_sort = ( { author => 'bart', title => 'skateboarding' }, { author => 'lisa', title => 'postmodernism' }, { author => 'marge', title => 'hairstyles' }, { author => 'lisa', title => 'THIS BOOK FIRST' }, { author => 'homer', title => 'donuts' }, { author => 'bart', title => 'coolness' } ); #this begs for a new structure. #lets use a hash. my %authors_books; #turn your AoH's into a HoA's #see perldsc for reference foreach (@things_to_sort){ push @{$authors_books{$_->{author}}}, $_->{title}; } #sort the books for each author foreach my $author (keys %authors_books){ @{$authors_books{$author}} = sort{ $a eq "THIS BOOK FIRST" && -1 or $b eq "THIS BOOK FIRST" && 1 or $a cmp $b }@{$authors_books{$author}}; } #figure out who to display first. my @display_keys = sort{ (grep /THIS BOOK FIRST/, @{$authors_books{$a}}) && -1 or (grep /THIS BOOK FIRST/, @{$authors_books{$b}}) && 1 or $a cmp $b } keys %authors_books; #display the information. foreach my $display_key (@display_keys){ print "$display_key books:\n"; foreach (@{$authors_books{$display_key}}){ print "\t$_\n"; } } exit;
The Output
lisa books: THIS BOOK FIRST postmodernism bart books: coolness skateboarding homer books: donuts marge books: hairstyles


-InjunJoel

P.S.
thanks davido for the sort idea.

"I do not feel obliged to believe that the same God who endowed us with sense, reason and intellect has intended us to forego their use." -Galileo


Comment on Re: Twisted sort requirements
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://527125]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2014-09-20 04:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (152 votes), past polls