in reply to Extract data based on dates and place in new file

An approach using Date::Simple
#!/usr/bin/perl use strict; use warnings; use Date::Simple qw/ today /; my $yesterday = today() - 1; my $wk_before = $yesterday - 7; for ($yesterday, $wk_before) { $_ = $_->strftime('%Y%m%d'); } while (<DATA>) { print if $_ ge $wk_before && $_ le $yesterday; } __DATA__ 20110801-23:42:01,4 20110802-23:42:01,4 20110802-23:45:01,3 20110802-23:48:01,1 20110802-23:51:01,1 20110802-23:54:01,2 20110802-23:57:01,3 20110803-00:00:01,3 20110810-23:42:01,4
This takes advantage of the fact that dates in this format, YYYYMMDD, are naturally sortable and can be string compared for greater than, less than or equality.

Replies are listed 'Best First'.
Re^2: Extract data based on dates and place in new file
by Anonymous Monk on Aug 11, 2011 at 17:23 UTC
    With a necessary correction
    #!/usr/bin/perl use strict; use warnings; use Date::Simple qw/ today /; my $today = today; my $wk_before = $today - 8; for ($today, $wk_before) { $_ = $_->strftime('%Y%m%d'); } while (<DATA>) { print if $_ ge $wk_before && $_ lt $today; } __DATA__ 20110801-23:42:01,4 20110802-23:42:01,4 20110802-23:45:01,3 20110802-23:48:01,1 20110802-23:51:01,1 20110802-23:54:01,2 20110802-23:57:01,3 20110803-00:00:01,3 20110810-23:42:01,4
      This code worked EXCELLENT, thanks so much. I just added my in and out file handles to extract from the file then place the extracted data in another file and it worked fine. Now have to figure out using PAR or pp so I can include the Date::Simple module in the script, they don't want us installing additional CPAN modules on the machines we are using as storage real estate is at a premium running off of compact flash. Darryl
        Glad it worked. :-) My only question is this covers Tues through the following Tuesday (8 days) and it seems that Tuesdays are getting reported twice. I am not familiar with PAR or pp. But, you could do this with a module that has been a part of the Perl core since the beginning of Perl 5.0. POSIX has the function strftime. It involves a little more code and isn't as simple as Date::Simple but will give the same results and you may not have to package it with your program (as it is part of the Perl core).
        #!/usr/bin/perl use strict; use warnings; use POSIX qw/ strftime /; my @dmy = (localtime)[3 .. 5]; # day-month-year my $today = strftime "%Y%m%d", (0) x 3, @dmy; $dmy[0] -= 8; # 8 days before my $wk_before = strftime "%Y%m%d", (0) x 3, @dmy; while (<DATA>) { print if $_ ge $wk_before && $_ lt $today; }