【发布时间】:2010-11-08 04:20:18
【问题描述】:
我正在写一些东西,允许用户搜索他们的日志。目前我有这个,其中 $in{'SEARCH'} 是他们正在搜索的字符串。
open(COMMAND, "grep \"$in{'SEARCH'}\" /home/$palace/palace/logs/$logfile | tail -n $NumLines |");
$f = <COMMAND>;
if ($f) {
print $Title;
print "<div id=log>\n";
do { print $f."<br>";} while ($f = <COMMAND>);
print "</div>\n";
} else {print $Error; }
close(COMMAND);
但是我注意到他们很容易通过使用双引号 (") 或反斜杠来欺骗脚本和 grep 命令出错。因此我添加了这段代码:
$in{'SEARCH'} =~ s|\\|\\\\|g;
$in{'SEARCH'} =~ s|"|\Q\"\E|g;
open(COMMAND, "grep \"$in{'SEARCH'}\" /home/$palace/palace/logs/$logfile | tail -n $NumLines |");
$f = <COMMAND>;
if ($f) {
print $Title;
print "<div id=log>\n";
do { print $f."<br>";} while ($f = <COMMAND>);
print "</div>\n";
} else {print $Error; }
close(COMMAND);
但是,我仍然遇到问题。 grep 命令不喜欢其搜索中的 \ 给出类似的错误
grep "\\" /home/test/palace/logs/chat.log
grep:尾部反斜杠
我是否应该继续尝试使用 grep 命令,如果是这样,有什么好的 Perl 函数可以帮助去除有助于 grep 命令的奇怪字符,比如让“成为 \”等。或者,我应该使用 Perl 代码来完成同样的事情,而不是乱七八糟,即使我已经阅读它不会像 grep 一样快?
更新:美国东部标准时间 2009 年 7 月 5 日下午 5:20
许多人贡献了代码,尤其是那些试图比系统 grep 更快的人。到目前为止,它仍然是最快的。以下是基准测试的结果:
使用系统 grep:
Top of file: 1 wallclock secs ( 0.00 usr 0.01 sys + 0.13 cusr 0.15 csys = 0.29 CPU)
Bottom of file: 1 wallclock secs ( 0.00 usr 0.00 sys + 0.21 cusr 0.18 csys = 0.39 CPU)
使用 Hypneks 示例(推送和移位):
Top of file: 4 wallclock secs ( 3.78 usr + 0.19 sys = 3.97 CPU)
Bottom of file: 4 wallclock secs ( 3.86 usr + 0.19 sys = 4.05 CPU)
使用我的 perl 示例(使用反向命令):
Top of file: 6 wallclock secs ( 4.76 usr + 1.45 sys = 6.21 CPU)
Bottom of file: 5 wallclock secs ( 3.93 usr + 1.44 sys = 5.37 CPU)
使用我的 File::ReadBackwards:
Top of file:11 wallclock secs (11.20 usr + 0.11 sys = 11.31 CPU)
Bottom of file: 1 wallclock secs ( 0.59 usr + 0.01 sys = 0.60 CPU)
使用 xcramps 示例(内置 grep):
Top of file: 9 wallclock secs ( 8.04 usr + 0.47 sys = 8.51 CPU)
Bottom of file: 8 wallclock secs ( 8.16 usr + 0.43 sys = 8.59 CPU)
【问题讨论】: