Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

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


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?

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2020-09-27 17:56 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (142 votes). Check out past polls.