Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Twisted sort requirements

by injunjoel (Priest)
on Feb 01, 2006 at 17:58 UTC ( [id://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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-24 02:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found