这个小的 Perl 脚本有什么作用? [英] What does this small Perl script do?
问题描述
有人能解释一下这个小的 Perl 脚本是做什么的吗?谢谢.
could someone explain what this small Perl script does? Thanks.
#!/usr/bin/perl
my ($file, $from, $to) = @ARGV;
my $fh;
my $matching = 0;
open($fh, $file) or die $!;
while(<$fh>)
{
if(/\Q$from\E/) { $matching = 1; }
if($matching) { print $_; }
if($matching && /\Q$to\E/) { last; }
}
close($fh);
推荐答案
这个脚本需要三个参数:
This script takes three parameters:
- 要读取的文件名
- 开始表达
- 结束表达
并打印(包括)开始表达式(第二个参数)和结束表达式(第三个参数)之间的所有内容.如果您有一个包含以下内容的文件:
and prints everything between (including) start expression (second parameter) and end expression (third parameter). If you have a file with the following content:
111
222
333
444
555
666
./script.pl filename 333 555
将打印 333
、444
和 555
.
my ($file, $from, $to) = @ARGV;
这一行将命令行参数分配给 $file
、$from
和 $to
.这会显示/为您提供所需的/不同的命令行参数.
This line assigns the command line arguments to $file
, $from
and $to
. This shows/gives you the required/different command line arguments.
my $fh;
my $matching = 0;
这两行只是声明并初始化了后面用到的两个变量.
These two lines just declare and initialize two variables used later.
open($fh, $file) or die $!;
尝试打开第一个传递的参数并将其分配给 $fh
或如果无法打开文件则退出程序.
Try to opens the first passed argument and assign it to $fh
or exit the program if the file can't be opened.
while(<$fh>)
{
这只是遍历文件内容
if(/\Q$from\E/) { $matching = 1; }
\Q
和 \E
是 perl 特定的正则表达式.这可以防止将特殊字符解释为正则表达式.如果当前行包含 $from
,则 $matching
设置为 1.
The \Q
and \E
are perl specific for regular expressions. This prevents interpreting special characters as regular expressions. If the current line contains contains $from
, $matching
is set to one.
if($matching) { print $_; }
如果设置了$matching
,则打印当前行
if $matching
is set, print the current line
if($matching && /\Q$to\E/) { last; }
如果设置了 $matching
并且 $to
在当前行,则退出循环
if $matching
is set and $to
is in the current line, exit the loop
}
close($fh);
关闭文件
这篇关于这个小的 Perl 脚本有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!