Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

sorting complex data

by mexnix (Pilgrim)
on Aug 08, 2001 at 23:04 UTC ( [id://103173]=perlquestion: print w/replies, xml ) Need Help??

mexnix has asked for the wisdom of the Perl Monks concerning the following question:

I've got a data structure like this:

$VAR1 = { 'news' => [ { 'title' => 'news1', 'content' => 'Article Contents...blah', 'date' => '08-03-01' }, { 'title' => 'news2', 'content' => 'Article Contents...blah', 'date' => '07-20-01' } ] };

I need to sort @$news by $data->{news}[$ele]{date} where $ele is the index in the array. I tried sort {$data->{news}[$a]{date} <=> $data->{news}[$b]{date}} @{$data->{news}};, but that didn't work. any ideas. Maybe need to change how the date is stored? I'm open to anything. thanks.

__________________________________________________
<moviequote name="Hackers">
The Plague: [...]Well let me explain the New World Order. Governments and corporations need people like you and me. We are samurai. The keyboard cowboys. And all those other people out there who have no idea what's going on are the cattle. Mooo!
</moviequote>

mexnix.perlmonk.org

Replies are listed 'Best First'.
Re: sorting complex data
by dga (Hermit) on Aug 08, 2001 at 23:30 UTC

    Two things come to mind right away ISO 8601 dates 20010720, 20010803 which will sort nicely or a bigger custom sorter.

    sub bydashdate { my($ma,$da,$ya)=split('-',$data->{news}[$a]{date}); my($mb,$db,$yb)=split('-',$data->{news}[$b]{date}); $ya <=> $yb || $ma <=> $mb || $da <=> $db; #select in y, m, d order +the lower date } #you would call sort &bydashdate ( @{$data->{news}} )

    This will break with your input if you have some old stuff from 99 around since that will sort after 00.

    Also there are many date parsing modules around on CPAN which are probably overkill for this but if its gets more complex may be handy.

Re: sorting complex data
by VSarkiss (Monsignor) on Aug 08, 2001 at 23:38 UTC

    I took your question to mean: "how can I apply Perl sort to this data structure?". This seems to sort your sample data correctly: sort { $a->{date} cmp $b->{date} } @{$data->{news}};Of course, this will do weird things if you have dates from different years since it sorts by month first (I presume those dates are mm-dd-yy). But it should point in the right direction if you want to use a better date comparison routine.

    HTH

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-03-29 05:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found