Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: sorting dates in YYYYMMDD format

by 2teez (Priest)
on Jul 04, 2013 at 07:12 UTC ( #1042349=note: print w/ replies, xml ) Need Help??


in reply to sorting dates in YYYYMMDD format

Hi learner@perl,
Since your output 20130501 20130401 20130601 is the same with what you want what 20130501 20130401 20130601 what next? You have solved your own problems. Except your expected output is different.

If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me


Comment on Re: sorting dates in YYYYMMDD format
Select or Download Code
Re^2: sorting dates in YYYYMMDD format
by learner@perl (Novice) on Jul 04, 2013 at 07:17 UTC
    Hi Masters.

    I solved the problem

    @dates = ('20130601', '20130401', '20130501'); my @sorted = map $_->[0], sort { $a->[1] cmp $b->[1] } map [ $_, join('', (/(..)(..)(....)/)[0,1,2]) ], @dates; # DD-MM-YYYY print "@sorted\n";

    Output

    20130401 20130501 20130601

    Thanks all

      Do you realize, that

      join('', (/(..)(..)(....)/)[0,1,2])

      does not change a string $_ of length 8 in any way? (Apart from burning CPU cycles...). The regex also does not fit very well when splitting YYYYMMDD into pieces.

        Yes, but the real strings that have to be sorted may not be that easy, containing e.g. rubbish at start, or some punctuation, or - worse - be of different, yet regexpable format. (I don't know for sure, just a thought).

      ..I solved the problem..
      Good... but why not just use sort just as you have been told previously on this post.
      Yes your regexes matched successfully, see

      but even at that it a lot of work.
      However, if you must use "Schwartzian transform", you can sort on the month, since the year is the same like this:
      use warnings; use strict; my @dates = ('20130601', '20130401', '20130501'); print join ' ' => map{$_->[0]} sort{$a->[1] <=> $b->[1]} map{/.{4}(.{2})/;[$_,$1]} @dates;
      But sincerely, for this use sort just like other monks told you.

      If you tell me, I'll forget.
      If you show me, I'll remember.
      if you involve me, I'll understand.
      --- Author unknown to me

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2014-12-21 22:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (108 votes), past polls