Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!!
This is part of my code where I need to parse the file names, get the date that comes as part of the file names and sort the dates after that, how can I do that here, tried with no success, any help please!!!!


opendir(DIR, $dir) or die $!; my $c_array_1=-3; while (my $file = readdir(DIR)) { $c_array_1++; # Just files next unless (-f "$dir/$file"); # Find files ending in .xml next unless ($file =~ m/\.xml$/); # Change to the date format 123_20070227_REFNUM.xml $file=~/^(\d{3})_(\d{4})(\d{2})(\d{2})_(.*?)/; $year_from= $2; $month_from= $3; $day_from = $4; $temp_date = month_from."/".$day_from."/".$year_from; sort $temp_date; # Sort date here and display:::: print "<option value=\"$c_array_1-$file\">$temp_date</option>" +; } closedir(DIR); print " </select>";


Thanks again!!!

Replies are listed 'Best First'.
Re: The Dates Sorting!
by wade (Pilgrim) on Mar 31, 2008 at 18:42 UTC

    There are a couple of issues, here. The first is that you always want to use

    use warnings; use strict;

    Next, you're using a scalar as the argument to your 'sort' routine. 'sort' is going to want an array and it'll return the sorted array.

    Next, you should consider using Date::Simple or (for more complex stuff) DateTime. To do this, you first install the module, then something like:

    use DateTime; my @dates; while(<...>) { my $date = DateTime->new(...); push @dates, $date; } my @sorted = sort @dates;

    Hope that helps!

    Update: fixed a typo

    --
    Wade
Re: The Dates Sorting!
by CountZero (Bishop) on Mar 31, 2008 at 20:57 UTC
    A date of the format mm/dd/yyyy cannot be easily sorted. Keep the date in the yyyymmdd format until sorted and then change it to the format you like.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: The Dates Sorting!
by toolic (Bishop) on Mar 31, 2008 at 18:57 UTC
    It would have been useful if you had provided some detailed information as to how your code failed, such as error or warning messages or a small sample of your output.

    Regardless, I see a few problems, in addition to the sort issue mentioned by others. You would have gotten warning messages had you used the strictures:

    use warnings; use strict;

    You would have been warned about month_from being a bareword and the Useless use of sort in void context. Also, use diagnostics can be used to get more verbose warning messages.

    Another problem is that you should always check if a regex match succeeded before using $1, $2, etc.

Re: The Dates Sorting!
by mhearse (Chaplain) on Mar 31, 2008 at 19:20 UTC
    Working with dates can be tricky. There are many modules available, but for something this simple doing it the long way should be find. The stat function can be used to get the mtime of a file. The mtime is an epoch value (your file's age in seconds since January 1, 1970). This can be used to sort the list. If you are dealing with subdirectores, use the File::Find module.
    [matt@test ~/testdir]$ stat -c %Y AMR.xml 1206990376
    #!/usr/bin/perl use strict; use POSIX qw(strftime); my $dir = '/your/dir'; opendir DIR, $dir or die $!; my @files = grep { /\.xml$/ && ! /^\./ } readdir DIR; closedir DIR; my %ds; for my $file (@files) { my $mtime = (stat("/your/dir/$file"))[9]; $ds{$file} = $mtime; } for my $sorted_file (sort { $ds{$a} <=> $ds{$b} } keys %ds) { my $file_date = strftime("%Y-%m-%d", localtime($ds{$sorted_file})) +; my $file_time = strftime("%H:%M:%S", localtime($ds{$sorted_file})) +; print qq[<option value="$sorted_file">$file_date $file_time</optio +n>\n]; }

      Good points.

      The only problem with the mtime stat on a file is that it may or may not have anything to do with the time encoded in the filename that the OP was interested in. So that may or may not be helpful for the OP.

      But if it turns out to, indeed, be applicable, then, to me, it sure would simplify the code and make the sorting even more compact.

      ack Albuquerque, NM
Re: The Dates Sorting!
by poolpi (Hermit) on Apr 01, 2008 at 09:45 UTC
    $ls *.xml 123_20070303_REFNUM.xml 123_20071225_REFNUM.xml 123_20080101_REFNUM.xml 923_20070227_REFNUM.xml
    #!/usr/bin/perl use strict; use warnings; use Date::Simple (':all'); use Data::Dumper; my $dir = q{/home/LarryTheLobster/}; opendir(DIR, $dir) or die $!; my @xml_files = sort { d8( (split /_/, $a)[1] ) cmp d8( (split /_/, $b)[1] ) } grep { -f and /[.]xml\z/ } readdir DIR; closedir DIR; print Dumper \@xml_files;
    Output: $VAR1 = [ '923_20070227_REFNUM.xml', '123_20070303_REFNUM.xml', '123_20071225_REFNUM.xml', '123_20080101_REFNUM.xml' ];

    hth,
    PooLpi

    'Ebry haffa hoe hab im tik a bush'. Jamaican proverb
      ++ for seeing that you don't need a regex to get hold of the date part.

      But why do you transform the date into a Date::Simple object in order to sort it? A date in the yyyymmdd format can be sorted numerically without any further ado.

      And of course, this kind of thing just screams for the Schwartzian Transform:

      use strict; use warnings; use Data::Dumper; my @xml_files = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, (split /_/, $_)[1]] } <DATA>; print Dumper \@xml_files; __DATA__ 123_20070303_REFNUM.xml 123_20071225_REFNUM.xml 123_20080101_REFNUM.xml 923_20070227_REFNUM.xml

      If there are only a few files to be sorted, it is of course overkill, but once the number of files increases the fact that you only have to do the split once for each file pays of.

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: The Dates Sorting!
by Fletch (Bishop) on Mar 31, 2008 at 18:39 UTC

    What part of the documentation for sort lead you to believe that calling it with a single element from what you wanted sorted would be at all fruitful?

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      The part that the code is going trough a while loop.