有人能告诉我一个有效的构造函数吗? DateTime::Format::Builder::Parser::Regex
#!/usr/bin/env perl
use warnings;
use 5.012;
use DateTime::Format::Builder;
use DateTime::Format::Builder::Parser::Regex;
my $parser = DateTime::Format::Builder->create_parser(
regex => qr/^(\d\d)(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)$/,
length => 13,
params => [ qw( year month day hour minute second ) ],
postprocess => \&_fix_year,
extra => {time_zone => "Australia/Sydney" },
constructor => ..., ###
);
sub _fix_year {
my %args = @_;
my ( $date, $p ) = @args{ qw( input parsed ) };
$p->{year} += $p->{year} > 69 ? 1900 : 2000;
return 1;
}
编辑: 更改了正则表达式,因此后期处理fix_year确实更有意义;
答案 0 :(得分:1)
我开始和你一样阅读doco。呼!
经过一些反向跟踪后,似乎这个模块在幕后有效地工作,而DateTime :: Format :: Builder将其称为插件。因此,使用创建自己的解析类的常规习惯用语,我在想:
#!/usr/bin/perl
package MyDateParser;
use common::sense;
use DateTime;
use DateTime::Format::Builder;
use DateTime::Format::Builder::Parser::Regex;
use DateTime::Format::Builder(
parsers => {
parse_datetime => {
regex => qr/^(\d\d\d\d)(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)$/,
length => 15,
params => [ qw( year month day hour minute second ) ],
postprocess => \&_fix_year,
extra => {time_zone => "Australia/Sydney" },
constructor => \&_construct_date,
}
}
);
sub _fix_year {
my %args = @_;
my ( $date, $p ) = @args{ qw( input parsed ) };
$p->{year} += $p->{year} > 69 ? 1900 : 2000;
return 1;
}
sub _construct_date {
my ($p, %extra) = @_;
use Data::Dumper; warn Dumper {p => $p, extra => \%extra};
return DateTime->new( %extra );
}
#-----------------------------------------------------------------------
package main;
my $dt = MyDateParser->parse_datetime('00101223T094517');
另请参阅DateTime :: Format :: Builder中的create_constructor()方法,该方法设置默认构造函数。