如何在不导入外部模块的情况下在Perl中转换日期格式?

前端之家收集整理的这篇文章主要介绍了如何在不导入外部模块的情况下在Perl中转换日期格式?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
可能是一个简单的答案:如何在不导入外部模块的情况下进行转换?我已阅读CPAN但无法明确指出执行以下操作的方法

Convert: 20080428 to 28-APR-08

有任何想法吗?

即使指导我阅读教程也会受到赞赏.

问候,
PIAS

解决方法

代码在Y10k中失败,但这应该足够好了.正则表达式可能更严格,但如果日期已经过验证(或将以新表格验证),则无关紧要.

#!/usr/bin/perl

use strict;
use warnings;

my @mon = qw/null JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC/;

my $d = "20080428";

$d =~ s/..(..)(..)(..)/$3-$mon[$2]-$1/;

print "date is now $d\n";

或者,如果你是疯了,想要在正则表达式中验证(需要Perl 5.10):

#!/usr/bin/env perl5.10.0

use strict;
use warnings;

my @mon = qw/null JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC/;

my $d = join '',@ARGV;

# only validates between 1600 and 9999
# because of calendar weirdness prior to 1600 
$d =~ s/
    ^
    (?:
        # non-leap years and everything but 29th of Feb in leap years
        (?:
            1[6-9]     (?<y> [0-9]{2}) | 
            [2-9][0-9] (?<y> [0-9]{2})
        )
        (?: #any month 1st through 28th
            (?: (?<m> 0[1-9] | 1[0-2]) (?<d> 0[0-9] | 1[0-9] | 2[0-8]) )
            | #or 30th of any month but 2
            (?: (?<m>0[13-9] | 1[0-2]) (?<d> 30) )
            | # or 31st of 1,3,5,7,8,10,or 12
            (?: (?<m>0[13578] | 1[02]) (?<d> 31) )
        )
        | # or 29th of Feb in leap years
        (?:
            (?: #centuries divisible by 4 minus the ones divisible by 100
                16          |    
                [2468][048] |
                [3579][26]
            )
            (?<y> 00)
            | #or non-centuries divisible by 4
            (?: 1[6-9] | [2-9][0-9] )
            (?<y>
                0[48]       | 
                [2468][048] |
                [13579][26]
            )
        )
        (?<m> 02) (?<d> 29)
    )
    $
/$+{y}-$mon[$+{m}]-$+{d}/x or die "invalid date: $d";

print "date is now $d\n";

猜你在找的Perl相关文章