0

I have a set of strings:

20120160323001.z1.xml
20120160324001.z1.xml
20120160322001.z1.xml

# The file format is XXXYYYYMMDDVVV.z1.xml where XXX is a
# medical code, YYYYMMDD is a date and VVV is a document
# version number

I want to sort the strings according to the date in descending order. So, the above strings after sorting will be:

20120160324001.z1.xml
20120160323001.z1.xml
20120160322001.z1.xml

I know how to sort arrays in Perl but given the complex file name I'm confused how I can sort these strings by date? Is it possible?

# The below sort function is not going to work for these filenames
sub rev_by_date  { 
    $b->[9+1] <=> $a->[9+1] 
}

my @sorted_files = sort rev_by_date @files;

Edit I use this regular expression to find these files: (?^:^201.*.z1.xml) but its not that useful for the date sorting function. In the date sorting function I dont know if comparing date strings will even work?

1
  • Regarding your regular expression, you should have no need for the enclosing (?^:...) which is primarily for writing a pattern that will be embedded within another. It resets all options to the defaults for the contents of the parentheses. You are also using dots—which will match any character—to match literal dots in the target string. Please don't copy code from the internet without understanding what it does. Commented Nov 17, 2017 at 1:52

2 Answers 2

3

You want to sort by the substrings matching the date part:

sub rev_by_date {
  substr($b, 3, 8) <=> substr($a, 3, 8);
}

my @sorted_files = sort rev_by_date @files;

...as long as the filenames match the format that you've described.

Sign up to request clarification or add additional context in comments.

Comments

0

Try

sort { substr($b, 3) cmp substr($a, 3) } @files;

This assumes @files contains strings. If it contains something else, you need to explain that. It retains the document version at the end of the sort key, so this will break ties.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.