Perl格式函数的解释

时间:2016-01-04 14:08:20

标签: perl

if( $start =~ /^(\d+).(\d+).(\d+)\s+(\d+):(\d+):(\d+)$/) {
        my @t = ( $6, $5, $4, $1, $2-1, $3);
        $event->{start} = timelocal(@t);
    }

任何人都可以向我解释这段代码吗?

2 个答案:

答案 0 :(得分:3)

你不明白哪一部分?

# $start is a string.
# We match $start against a regular expression.
# The regular expression looks for:
# * The start of the string [^]
# * One or more digits [(\d+)]
# * Any single character [.]
# * One or more digits [(\d+)]
# * Any single character [.]
# * One or more digits [(\d+)]
# * One or more whitespace characters [\s+]
# * One or more digits [(\d+)]
# * A colon [:]
# * One or more digits [(\d+)]
# * A colon [:]
# * One or more digits [(\d+)]
# * The end of the string [$]
# Each of the sets of digits that are matched are "captured".
# That means that if the regex matches, the digits are stored
# in variables. The first set of digits is put in $1, the
# second set of digits is put in $2, and so on.
if( $start =~ /^(\d+).(\d+).(\d+)\s+(\d+):(\d+):(\d+)$/) {
    # If the regex matches, then we execute this block of code.
    # We copy the capture variables into an array called @t
    # We copy them in a different order to how they appear
    # in the original string.
    # We subtract 1 from $2 before using it.
    my @t = ( $6, $5, $4, $1, $2-1, $3);
    # We pass @t to a function called timelocal() which we
    # have loaded from a module called Time::Local.
    # timelocal() takes a list of date/time values and returns
    # the number of seconds since 00:00 on 1970-01-01.
    # $event is a hash reference. We store the number of seconds
    # as the value against the "start" key in the referenced 
    # hash.
    $event->{start} = timelocal(@t);
}

由此,我们可以确定原始字符串可能包含格式为DD MM YYYY HH:MM:SS的时间戳,我们将其转换为自1970-01-01 00:00以来的秒数。

使用Time::Piece中的strptime可以更简单地实现这一点。

use Time::Piece;

$event->{start} = Time::Piece->strptime($str, '%d $m %Y %H:%M:%S')->epoch;

答案 1 :(得分:2)

看起来有人重新实现了POSIX::strptime。特别是,它只是将原始字符串中的各种数字范围匹配并捕获到编号的捕获缓冲区中。