2012-08-15 98 views
0

我有這樣的PERL Switch..case聲明:Perl的Case語句的日期範圍

switch ($today) 
{ 
    case "14-Aug-2012" { do A } 
    case "15-Aug-2012" { do B } 
}#end switch 

我的問題是,「做B」的語句是同爲15月 - 2012年01喜歡辛2012。我怎麼說這些日期之間的情況,所以我不必在不同的日子重寫相同的東西,並使我的腳本很長?

我已經放入了整個腳本,所以有人可以幫助我使用我必須管理我的問題。

use Date::Calc 
use Switch 

#connect to database... 

my @date_today=Today(); 
my $today=substr(Date_to_Text(@date_today),4,11); 

Switch($today) 
{ 
    case "14-Aug-2012" {Do A} 
    case "15-Aug-2012" {Do B} 
    case ... 
    case ... 
    case ... 
} 

最後3條case語句應該做的:

between 16-Aug-2012 and 28-Sep-2012 {do C} 
    between 29-Sep-2012 and 26-Oct-2012 {do D} 
    between 27-Oct-2012 and 09-Nov-2012 {do E} 
+3

該語言稱爲Perl或Perl ...不是PERL。 – dgw 2012-08-15 09:55:03

+1

@dgw - 實際上,該語言只被稱爲「** Perl **」。 「perl」是解釋器可執行文件的名稱,而不是語言:) – DVK 2012-08-15 13:47:54

+0

我忘了補充說我使用的是Date :: Calc軟件包。讓我把第一部分......日期::計算器 – 2012-08-16 08:02:32

回答

0

使用UNIX時間戳,而不是日期字符串。時間戳是整數,可以很容易地劃分爲日期範圍(並使用localtime()重新格式化)。

例如,使用Time::Local及其timelocal()功能將您的字符串轉換成時間戳:

use Time::Local; 
my %months = (# necessary because timelocal() expects month numbers, not strings 
    'Jan' => 0, 
    'Feb' => 1, 
    'Mar' => 2, 
    'Apr' => 3, 
    'May' => 4, 
    'Jun' => 5, 
    'Jul' => 6, 
    'Aug' => 7, 
    'Sep' => 8, 
    'Oct' => 9, 
    'Nov' => 10, 
    'Dec' => 11 
); 
my $today = '15-Aug-2012'; 
my @t = $today =~ /(\d{4})-(\w{3})-(\d{4})/; 
$t[1] = $months{$t[1]}; # turn string into integer 
my $timestamp = timelocal(0, 0, 0, @t[0, 1, 2]); # sec, min, hr, day, month, year 
2

使用的軟件工程方法。

如果您需要在整個日期範圍內做同樣的事情,請將該範圍的ID用作謹慎的值以供選擇。然後有一個子程序告訴你該日期的範圍ID是什麼:

sub range_for_date { 
    my $date = shift; 
    # Compute the range value in some discreet subset 
    # How to compute it is somewhat irrelevant 
    #  and can be asked separately if you have no idea 
    # discreet subset can be an index 1..N, ecpoch timestamps, 
    # or a somehow-encoded range end date (e.g. "20121001" is easy) 
    # For the switch example below we will assume end dates 

    return $range_id; # in "20121001" format 
} 

switch (range_for_date($today)) { 
    case "20121001" { do B; } 
    case "20120110" { do A; } 
} 
0

這是另一種做法,可能會更簡單一些。它只是將日期轉換爲YYYYMMDD格式,從而可以對它們進行排序/比較。

sub sortable_date 
{ 
    my %months; 
    @months{ 
     'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' 
    } = ('01'..'12'); 

    if (shift() =~ /^(\d{1,2})-(\w{3})-(\d{4})/ and exists $months{$2}) 
    { 
     return "$3$months{$2}$1"; 
    } 
    else { die "invalid date format!"; } 
} 

switch (sortable_date($today)) 
{ 
    case sortable_date("14-Aug-2012")     { do A } 
    case ($_[0] >= sortable_date("15-Aug-2012") and 
      $_[0] <= sortable_date("01-Oct-2012"))  { do B } 
} 

我會推薦mpe的方法,如果你打算在日常工作中做很多工作,儘管如此。