我有一个单行的Perl脚本(Perl v5.10.1),其行为方式我无法理解或解释:
$ cat packer-build.log |
> perl -MPOSIX -pe \
> 's/^(\d+)/my $x = strftime("%Y-%m-%d %H:%M", localtime($1)); print "$x "/e' | tail -5
2017-06-21 11:11 1,,error-count,1
2017-06-21 11:11 1,,ui,error,\n==> Some builds didn't complete successfully and had errors:
2017-06-21 11:11 1,amazon-ebs,error,unexpected EOF
2017-06-21 11:11 1,,ui,error,--> amazon-ebs: unexpected EOF
2017-06-21 11:11 1,,ui,say,\n==> Builds finished but no artifacts were created.
未过滤的输出:
$ tail -5 packer-build.log
1498007467,,error-count,1
1498007467,,ui,error,\n==> Some builds didn't complete successfully and had errors:
1498007467,amazon-ebs,error,unexpected EOF
1498007467,,ui,error,--> amazon-ebs: unexpected EOF
1498007467,,ui,say,\n==> Builds finished but no artifacts were created.
请注意,未经过滤的输出中不存在1
之后的2017-06-21 11:11
。
导致打印的原因是什么?如何修改代码以便我将字段1中的纪元时间替换为人类可读的输出?
答案 0 :(得分:5)
在替换中使用/e
时,匹配将替换为替换代码评估的内容。您在代码中调用print()
,并且print()
在打印成功时返回真值(1)。这就是你在替换中所看到的。
但你不需要print()
。用以下代码替换您的代码:
s/^(\d+)/my $x = strftime("%Y-%m-%d %H:%M", localtime($1)); $x/e
或者,甚至更简单:
s/^(\d+)/strftime("%Y-%m-%d %H:%M", localtime($1))/e