I have code snippet which I modified, from here:
How can I get this week's dates in Perl?
I am trying to generate dates, preferably starting today, up to any number of days. My code works from tomorrow up to 10 days. I do generate an array @dates
containing strings like Sat 08 Apr 2023
.
I am not able to extract a datestring like $dates[0]
.
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw{strftime};
my @dates;
my $dates;
my $time = time ();
my $seconds = 24*60*60;
my @time = gmtime ();
for (1..10){
$time += $seconds;
my @dates = gmtime ($time);
print strftime ("%a %d %b %Y\n", @dates);
}
The following code is the minimum change to do what you want, but as @brian d foy already pointed out, will not work in all circumstances:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw{strftime};
my @dates;
my $time = time ();
my $seconds = 24*60*60;
for (1..10){
push @dates, strftime ("%a %d %b %Y\n", gmtime ($time));
$time += $seconds;
}
print @dates;
produces:
Sun 09 Apr 2023
Mon 10 Apr 2023
Tue 11 Apr 2023
Wed 12 Apr 2023
Thu 13 Apr 2023
Fri 14 Apr 2023
Sat 15 Apr 2023
Sun 16 Apr 2023
Mon 17 Apr 2023
Tue 18 Apr 2023
The code below, apart from being shorter, should also work in the corner cases that @brian d foy was talking about.
#!/usr/bin/perl
use strict;
use warnings;
use Date::Calc qw( Today Add_Delta_Days Date_to_Text );
my @dates;
my @date = Today();
for (0..9){
push @dates, Date_to_Text( Add_Delta_Days(@date,$_) )."\n";
}
print @dates;