我有以下循环来计算当前周的日期并打印出来.它有效,但我在Perl的日期/时间可能性游泳,想要了解是否有更好的方法.这是我写的代码:
#!/usr/bin/env perl use warnings; use strict; use DateTime; # Calculate numeric value of today and the # target day (Monday = 1,Sunday = 7); the # target,in this case,is Monday,since that's # when I want the week to start my $today_dt = DateTime->Now; my $today = $today_dt->day_of_week; my $target = 1; # Create DateTime copies to act as the "bookends" # for the date range my ($start,$end) = ($today_dt->clone(),$today_dt->clone()); if ($today == $target) { # If today is the target,"start" is already set; # we simply need to set the end date $end->add( days => 6 ); } else { # Otherwise,we calculate the Monday preceeding today # and the Sunday following today my $delta = ($target - $today + 7) % 7; $start->add( days => $delta - 7 ); $end->add( days => $delta - 1 ); } # I clone the DateTime object again because,for some reason,# I'm wary of using $start directly... my $cur_date = $start->clone(); while ($cur_date <= $end) { my $date_ymd = $cur_date->ymd; print "$date_ymd\n"; $cur_date->add( days => 1 ); }
如上所述,这是有效的,但它是最快还是最有效的?我猜测速度和效率可能不一定在一起,但您的反馈非常感谢.
解决方法
原文地址:https://www.jb51.cc/Perl/171709.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。