In Perl how to find the date of the previous Monday for a given date?

后端 未结 9 1028
深忆病人
深忆病人 2020-12-11 03:48

I am looking for a Perl script which can give me the last Monday for any specified date.

e.g. For date 2011-06-11, the script should return 2011-06-06

9条回答
  •  一生所求
    2020-12-11 04:21

    Pretty simple stuff using the standard Perl library.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use 5.010;
    
    use Time::Local;
    use POSIX 'strftime';
    
    my $date = shift || die "No date given\n";
    
    my @date = split /-/, $date;
    $date[0] -= 1900;
    $date[1]--;
    
    die "Invalid date: $date\n" unless @date == 3;
    
    my $now = timelocal(0, 0, 12, reverse @date);
    
    while (strftime('%u', localtime $now) != 1) {
      $now -= 24 * 60 * 60;
    }
    

    I'll leave it as an exercise for the reader to look up the various modules and functions used.

    It's probably even simpler if you use DateTime.

提交回复
热议问题