我正在尝试使用带Date::Day的Perl将指定日期转换为一周中的相应日期。
输入字符串的格式为:October 24, 2011; March 12, 1989; November 26, 1940
。
我编写了一个脚本,它将解析上面的输入并将每个日期转换为Date::Day::day()
接受的格式。
此子例程接受格式为mm,dd,yyyy
的输入。我用哈希做了这个。最近在stackoverflow上发布了一个关于此查询的线程,并且在其他成员的帮助下,能够做到这一点。
这是我的脚本,它为每个日期返回ERR,而不是返回与日期对应的星期几。
传递给day()子例程的参数的输入格式似乎有问题。
以下是我正在使用的Perl模块的更多文档: http://helpspy.com/c.m/programming/lang/perl/cpan/c06/Date/Day/d_1/
我很想知道,我哪里错了。在将日期作为参数传递给day()子例程之前,是否必须对日期进行一些修改?
#!/usr/bin/perl
use Date::Day;
use strict;
use warnings;
my @arr;
print "Enter the string: ";
my $str=<>;
chomp $str;
my @dates= split /; /,$str;
my %days= ("January",1,"February",2,"March",3,"April",4,"May",5,"June",6,"July",7,"August",8,"September",9,"October",10,"November",11,"December",12);
my @output = map {
my $pattern=$_;
$pattern =~ s/(\S*)\s/$days{$1}, /;
$pattern =~ s/\s//g;
$pattern
} @dates;
print &day(11,9,1987); # for test purpose and it returns correct value
foreach $output (@output)
{
chomp $output;
my $result=&day($output);
push(@arr,$result);
}
foreach my $arr (@arr)
{
print $arr."; ";
}
上述脚本的输出是:ERR;呃; ERR;
答案 0 :(得分:5)
Date::Day看起来像一个相当古老的模块。它是在九年前的最后一次更新。这并不是说它已经坏了,但是现在DateTime系列模块几乎可以处理你想要的任何日期/时间处理。我强烈建议你去看看。
以下是使用DateTime :: Format :: Strptime解决问题的示例。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use DateTime::Format::Strptime;
my $dt_parser = DateTime::Format::Strptime->new(
pattern => '%B %d, %Y'
);
while (<DATA>) {
chomp;
my $dt = $dt_parser->parse_datetime($_);
say $dt->day_name;
}
__END__
October 24, 2011
March 12, 1989
November 26, 1940
答案 1 :(得分:3)
您正在将字符串传递给子&day
。
这是重写:
#!/usr/local/bin/perl
use Data::Dump qw(dump);
use strict;
use warnings;
use Date::Day;
print "Enter the string: ";
my $str=<>;
chomp $str;
my @dates= split /; /,$str;
my %days = ("January",1,"February",2,"March",3,"April",4,"May",5,"June",6,"July",7,"August",8,"September",9,"October",10,"November",11,"December",12);
my @output = map {
my @l = split/[ ,]+/;
$l[0] = $days{$l[0]};
[@l];
} @dates;
my @arr;
foreach my $date(@output) {
push @arr, &day(@$date);
}
dump@arr;
<强>输出:强>
("MON", "SUN", "TUE")