简体   繁体   English

带有 -pl 命令行选项的 Perl 单行程序

[英]Perl one-liner with -pl command-line options

I'm running我在跑

perl -ple '$_=length' datafile

The datafile contains the following:数据文件包含以下内容:

algorithm
student government
Fiumichino

The result is that it prints结果是它打印

9
18
10

What do the -p and -l options do? -p 和 -l 选项有什么作用? Also, what is $_ ?另外,什么是$_

$_ is the default input and pattern-searching variable. $_是默认的输入和模式搜索变量。 -p is a command line switch that puts an implicit while(<>) loop around your program, with a print statement at the end. -p是一个命令行开关,它在你的程序周围放置一个隐式的while(<>)循环,最后是一个打印语句。 The -l switch sets $/ and $\\ to "\\n" (newline) and chomp s your input, or in layman's terms, it handles newlines for you. -l开关将$/$\\为 "\\n"(换行符)并chomp s 您的输入,或者用外行的话来说,它为您处理换行符。

The diamond operator <> is "magic" in that it automatically chooses your input channel.菱形运算符<>是“神奇的”,因为它会自动选择您的输入通道。 If your script has arguments, it will interpret it as a file name, and open that file and read it.如果您的脚本有参数,它会将其解释为文件名,然后打开该文件并读取它。 If not, it checks STDIN.如果没有,它会检查 STDIN。 In your case, it opens the file "datafile".在您的情况下,它会打开文件“数据文件”。

What that oneliner does is read each line of datafile and sets $_ to the length of $_ (since length uses $_ if no argument is supplied), then prints that number.什么oneliner所做的是读取数据文件和设置的每一行$_到的长度$_ (因为length使用$_如果没有提供任何参数),然后打印出号。

You can deparse the one-liner and see what the code looks like:您可以解析 one-liner 并查看代码的样子:

$ perl -MO=Deparse -ple '$_=length' datafile
BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined($_ = <ARGV>)) {
    chomp $_;
    $_ = length $_;
}
continue {
    die "-p destination: $!\n" unless print $_;
}
-e syntax OK

-p causes the Perl interpreter to loop over its input and run the code (supplied via -e in this case) once per line, instead of just once total. -p使 Perl 解释器循环其输入并每行运行一次代码(在这种情况下通过-e提供),而不是总共运行一次。 At the bottom of each loop iteration it prints the line out.在每次循环迭代的底部,它会打印出该行。

The actual line is read into the $_ variable, and the contents of that variable are what is printed at the bottom of the loop body, so by changing the contents of $_ inside the loop, you can change what is output.实际行被读入$_变量,该变量的内容是打印在循环体底部的内容,因此通过更改循环内$_的内容,您可以更改输出的内容。

The length operator with no argument counts the length of $_ .没有参数的length运算符计算$_的长度。 So $_=length replaces the line with its length before it gets printed.所以$_=length在打印之前用它的$_=length替换该行。

-l just causes the Perl interpreter to remove newlines from input (so they won't be counted in the length values here) and automatically put them back on output (otherwise the output would be jammed together as 91810). -l只是使 Perl 解释器从输入中删除换行符(因此它们不会被计入此处的长度值)并自动将它们放回输出(否则输出将作为 91810 卡在一起)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM