http://qs321.pair.com?node_id=1130647

jason.printer has asked for the wisdom of the Perl Monks concerning the following question:

Hello-- I have solved my problem, but I don't know how. (I have kept it below for ...posterity?) What's going on here? :) When I change my sort function to the following it works as expected, sorting the dates. What is the difference between parentheses absent and parentheses present?

Working code:

sub sortByDate { #get dates. will look like this: date:"2015-02-16", date:"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); }

Original post:

=========

I am newish to Perl and trying to sort a file but it is behaving unexpectedly. I have a file which has several items in json format (not in date order and with some blank lines), for example:

{ date:"2015-03-01", content:"asdf" } { date:"2015-05-01", content:"erwa" } { date:"2015-01-02", content:"erts" } { date:"2014-04-02", content:"w34r" }

when I run my code intended to sort by date, it seems to sort the file in another way which I don't quite understand. It puts all the blank lines first, and then all the other lines stay in the order they were in the file. Here is my code:

#!/user/bin/perl use strict; use warnings; # open file open (MYFILE, '<jsonfile.json') or print ("Can't open file."); # pull into list my @events = <MYFILE>; # close file close (MYFILE); # organize by date sub sortByDate { #get dates. will look like this: date:"2015-02-16", date:"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); } @events = sort sortByDate @events; &printDates; <code> <p>When run, I get</p> <code> 2015-03-01 2015-05-01 2015-01-02 2014-04-02
Any help would be appreciated. I am new to custom sorts and regex.