2011-10-25 43 views
1

我試圖將給定日期轉換爲使用Perl與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;呃;呃;

回答

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); 
} 
[email protected]; 

輸出:

("MON", "SUN", "TUE") 
+0

很好用! +1 –

5

Date::Day看起來像一個相當老的模塊。這是近9年前最後更新的。這並不是說它已經壞了,但是現在這些模塊家族幾乎可以處理任何你想要的日期/時間處理。我強烈建議你看看那些。

下面是使用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

DateTime可能是有史以來使用任何語言編寫的最好的軟件之一。 –

相關問題