sub sortByDate { #get dates. will look like this: date:"2015-02-16", "YYYY-MM-DD", my $aDate = $a =~ /date:\"(\d{4}\-\d{2}\-\d{2})"/; my $bDate = $b =~ /date:\"(\d{4}\-\d{2}\-\d{2})"/; return ($aDate cmp $bDate); }
...should contain...
my($aDate) = $a =~ /date\"(\d{4}-\d{2}-\d{2})"/; my($bDate) = $b =~ /date\"(\d{4}-\d{2}-\d{2})"/;
The regexp binding operator returns true/false (1 or 0) in scalar context, and the match contents in list context. The parens around your variable names place the return value of the =~ operator into list context.
By the way, even for small bits of JSON, I'd be inclined to convert them to a datastructure as the first thing I do, rather than treating the json as text.
Update: An example of treating the data as JSON:
use strict; use warnings; use JSON; use Data::Dump; my @data; while (<DATA>) { next unless /\N/; push @data, decode_json($_); } print "Unsorted:\n"; dd \@data; my @sorted = sort { $a->{date} cmp $b->{date} } @data; print "\nSorted:\n"; dd \@sorted; __DATA__ { "date":"2015-03-01", "content":"asdf" } { "date":"2015-05-01", "content":"erwa" } { "date":"2015-01-02", "content":"erts" } { "date":"2014-04-02", "content":"w34r" }
...produces the following output:
Unsorted: [ { content => "asdf", date => "2015-03-01" }, { content => "erwa", date => "2015-05-01" }, { content => "erts", date => "2015-01-02" }, { content => "w34r", date => "2014-04-02" }, ] Sorted: [ { content => "w34r", date => "2014-04-02" }, { content => "erts", date => "2015-01-02" }, { content => "asdf", date => "2015-03-01" }, { content => "erwa", date => "2015-05-01" }, ]
I did have to fix up your JSON, but I assume the real data you are working with is real JSON, not pseudo-JSON as the post seems to show. There are many reasons why I would prefer an approach that treats the input JSON as JSON rather than as strings, including:
Dave
In reply to Re: sorting a file by a date:"YYYY-MM-DD" field with cmp
by davido
in thread sorting a file by a date:"YYYY-MM-DD" field with cmp
by jason.printer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |