如果我可以为一个模式匹配做两件不同的事情,我会徘徊: 我正在阅读包含以下行的文件:
( 1,<2010-01-12 15:19:51.32 +0100>,<marc>,<telescope1>,
我正在尝试这个策略:
open(FILE, "<tmpinp.txt");
while (<FILE>){
{$expstart = timelocal($6,$5,$4,$2,($3-1),$1) && $usr=$7} if
/.+1,<(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2}).*>,<(\S+)>,<(\S+)>.+\n/;
};
close(FILE);
};
因此我想获得纪元时间和用户名(本例中为marc) 在一次运行。它只是不起作用。任何帮助!?
Thanx很多!
答案 0 :(得分:4)
最明确的方法是使用if
的非后缀形式:
while (<FILE>){
if (/.+1,<(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2}).*>,<(\S+)>,<(\S+)>.+\n/) {
# this is a block; you can put as many statements in here as you want
$expstart = timelocal($6,$5,$4,$2,($3-1),$1);
$usr = $7;
}
}
如果你真的,真的想要出于某种原因使用postfix if
,你仍然可以将它用于一个块,感谢do
:
while (<FILE>){
do {
# this is a block; you can put as many statements in here as you want
$expstart = timelocal($6,$5,$4,$2,($3-1),$1);
$usr = $7;
} if /.+1,<(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2}).*>,<(\S+)>,<(\S+)>.+\n/;
}
或者您可以以某种深奥的方式将两个陈述合并为一个。这对于在非常紧密的循环内微观优化条件非常有用。例如,您可以使用逗号运算符组合两个分配:
while (<FILE>){
($expstart = timelocal($6,$5,$4,$2,($3-1),$1)), ($usr = $7)
if /.+1,<(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2}).*>,<(\S+)>,<(\S+)>.+\n/;
}
或者,如果您知道timelocal
将始终返回单个标量值(从不返回零或多个值的列表),那么您可以使用列表赋值来设置$expstart
和{{ 1}}:
$usr
或者如果您知道while (<FILE>){
($expstart, $usr) = (timelocal($6,$5,$4,$2,($3-1),$1), $7)
if /.+1,<(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2}).*>,<(\S+)>,<(\S+)>.+\n/;
}
将始终返回“true”值(即不是0,或空字符串或undef),您可以在尝试时使用timelocal
:
&&
TIMTOWTDI。
答案 1 :(得分:0)
这个怎么样:
#!/usr/bin/perl
use strict;
use warnings;
use Time::Local;
open(FILE, "<tmpinp.txt");
while (<FILE>){
if ($_ =~ /^.+1,<(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2}).*?>,<(\S+)>,<(\S+)>.+$/) {
print join(' => ', timelocal($6,$5,$4,$2,$3-1,$1), $7) . "\n";
}
}
close(FILE);
打印:
1291213191 => marc