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

Может кто-нибудь объяснить мне этот код?Объяснение для функции формата Perl

+3

выглядит как строка $ start - это отметка времени в формате «dd.mm.yy HH: MM: SS». Затем вы назначаете «стартовый» ключ $ event hashref (или объекта) на временную метку времени того времени. –

+4

В какой части у вас проблемы с пониманием? – ikegami

ответ

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.

Этого можно добиться гораздо проще, используя strptime от Time::Piece.

use Time::Piece; 

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

Похоже, что кто-то чрезмерно плохо переоценивает POSIX::strptime. В частности, он просто сопоставляет и захватывает различные диапазоны чисел из исходной строки в пронумерованные буферы захвата.

Смежные вопросы