0

我有下面的脚本。输入数据是日期。我需要做的是过滤掉不超过一周的日期并将其替换为“0”,并将两周的日期替换为“1”。其他日期应该被删除(我没有得到它)​​。这是脚本,但它似乎不起作用:

    use Date::Parse;
    use Date::Format;
    use Date::Manip;

    sub f {

    my $x = shift;
    my $env = shift;

    my $time = str2time($x);
    my $oneweekold = str2time(time2str('%Y-%m-%d 00:00:00', (time()-60*60*24*7)));
    my $twoweeksold = str2time(time2str('%Y-%m-%d 00:00:00', (time()-60*60*24*14)));

    return '0' if $time < $oneweekold;
    return '1' if $time < $twoweeksold;

    return $x;

    }

谢谢你的帮助。

4

1 回答 1

2

您要求一个返回三个值的 sub,其中一个值表示需要过滤,其中两个值是实际值。这是一团糟。

相反,让我们编写一个返回几周前的子程序。您可以对其进行过滤,并基于此设置输出格式。

use strict;
use warnings;
use feature qw( say );

use Date::Parse qw( str2time );
use DateTime    qw( );

# ...    
# -2 = 7..13 days from now.
# -1 = 0.. 6 days from now.
#  0 = 1.. 7 days ago.
#  1 = 8..14 days ago.
# ...
sub weeks_ago {
   my ($ref, $dt) = @_;
   if ($dt >= $ref) {
      return -int( ( $ref->delta_days($dt)->in_units('days') + 7 ) / 7 );
   } else {
      return int( ( $ref->delta_days($dt)->in_units('days') - 1 ) / 7 );
   }
}

my $ref = DateTime->today( time_zone => 'local' );

my $dt = DateTime->from_epoch( epoch => str2time('2013:03:27T08:08:17.1823213') );
my $weeks_ago = weeks_ago($ref, $dt);
if (0 <= $weeks_ago && $weeks_ago <= 1) {   # Filtering
   say $weeks_ago;                          # Formatting (Actually, none needed)
}
于 2013-02-26T11:18:12.067 回答