Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

What is the optimal way to loop between two dates in Perl?

What is the optimal/clearest way to loop between two dates in Perl? There are plenty of modules on CPAN that deal with such matter, but is there any rule of thumb for iterating between two dates?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For everything that uses Date manipulation DateTime is probably the best module out there. To get all dates between two dates with your own increment use something like this:

#!/usr/bin/env perl
use strict;
use warnings;
use DateTime;

my $start = DateTime->new(
    day   => 1,
    month => 1,
    year  => 2000,
);

my $stop = DateTime->new(
    day   => 10,
    month => 1,
    year  => 2000,
);


while ( $start->add(days => 1) < $stop ) {
    printf "Date: %s
", $start->ymd('-');
}

This will output:

Date: 2000-01-02
Date: 2000-01-03
Date: 2000-01-04
Date: 2000-01-05
Date: 2000-01-06
Date: 2000-01-07
Date: 2000-01-08
Date: 2000-01-09

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
by (100 points)

Please, will you tell me how the cycle:

while ( $start->add(days => 1) < $stop )

start in 1 because I use your code and it had been started in the date: 2000-01-02 not 2000-01-01

Thanks a lot

Regards

Xochitl

my $start = DateTime->new(
    day   => 1,
    month => 1,
    year  => 2000,
);

Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...