Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting by mmyy (month and year)

Tags:

sorting

perl

I'm looking for a logical (not additional module) to sort by such format. I have a list of strings which looks like:

asdadasBBBsfasdasdas-0112
asdanfnfnfnfnf222ads-1210

etc. I cant just sort by the numbers, because, for instance: 812 > 113 (812 = August 2012, 113 = January 2013, so its incorrect)

any good strategy??

thanks,

like image 383
snoofkin Avatar asked May 20 '12 12:05

snoofkin


People also ask

How do you Sort dates by month and year?

On the Data tab, in the Sort & Filter group, click Sort. In the Sort dialog box, do the following: Under Column, select the name of the column that contains the month names. Under Sort on, choose Cell Values.

How do I Sort Excel date by month and year?

Drag down the column to select the dates you want to sort. Click Home tab > arrow under Sort & Filter, and then click Sort Oldest to Newest, or Sort Newest to Oldest.

How do you Sort dates by month and day not year?

Insert a blank column next to your Date column. Assuming your first date is in cell A4, in the blank column, enter the formula: =TEXT(A4,"MMDD") Copy this formula down to the bottom of your data. Sort your data on this column.

How do I Sort month name by month number?

Go to the database tab, select month name column from your calendar table. Select the modeling tab and then "Sort by Column" and select your month number column. Month name should now appear in the correct order.


2 Answers

A schwartzian transform would be a huge waste here. This similar construct whose name I can never remember would be way better.

my @sorted =
   map substr($_, 4),
    sort
     map substr($_, -2) . substr($_, -4, 2) . $_,
      @unsorted;

Using the match operator instead of substr:

my @sorted =
   map substr($_, 4),
    sort
     map { /(..)(..)\z/s; $2.$1.$_ }
      @unsorted;
like image 140
ikegami Avatar answered Oct 17 '22 02:10

ikegami


How about Schwartzian transform:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dump qw(dump);

my @list = (
    'asdadasBBBsfasdasdas-0112',
    'asdanfnfnfnfnf222ads-1210',
    'asdanfnfnfnfnf222ads-1211',
    'asdanfnfnfnfnf222ads-1010',
    'asdanfnfnfnfnf222ads-1011',
);

my @sorted = 
    map  { $_->[0] }
    sort { $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2] }
    map  { /-(\d\d)(\d\d)$/; [$_, $2, $1] } @list;
dump @sorted;

output:

(
  "asdanfnfnfnfnf222ads-1010",
  "asdanfnfnfnfnf222ads-1210",
  "asdanfnfnfnfnf222ads-1011",
  "asdanfnfnfnfnf222ads-1211",
  "asdadasBBBsfasdasdas-0112",
)
like image 39
Toto Avatar answered Oct 17 '22 02:10

Toto