<>的用途是什么在Perl? [英] What's the use of <> in Perl?
问题描述
在Perl中<>的用途是什么.如何使用它 ? 如果我们简单地写
What's the use of <> in Perl. How to use it ? If we simply write
<>;
和
while(<>)
程序在两种情况下都做什么?
what is that the program doing in both cases?
推荐答案
上面的答案都是正确的,但是如果您了解一般的UNIX命令行用法,则可能会更清楚地看到它.想要命令在多个文件上运行是非常.例如
The answers above are all correct, but it might come across more plainly if you understand general UNIX command line usage. It is very common to want a command to work on multiple files. E.g.
ls -l *.c
命令行外壳程序(bash等)将其转换为:
The command line shell (bash et al) turns this into:
ls -l a.c b.c c.c ...
换句话说,除非模式不匹配,否则ls永远不会看到"* .c".在命令提示符(而不是perl)上尝试以下操作:
in other words, ls never see '*.c' unless the pattern doesn't match. Try this at a command prompt (not perl):
echo *
您会发现您没有得到*.
you'll notice that you do not get an *.
因此,如果外壳程序为您提供了一堆文件名,并且您想依次浏览每个人的数据,则perl的<>运算符为您提供了一种不错的方式...下一个文件的下一行(如果没有命名文件,则为stdin)进入$ _(默认标量).
So, if the shell is handing you a bunch of file names, and you'd like to go through each one's data in turn, perl's <> operator gives you a nice way of doing that...it puts the next line of the next file (or stdin if no files are named) into $_ (the default scalar).
这是一个穷人的情节:
while(<>) {
print if m/pattern/;
}
运行此脚本:
./t.pl *
将打印出与给定模式匹配的所有文件的所有行.
would print out all of the lines of all of the files that match the given pattern.
cat /etc/passwd | ./t.pl
将使用cat生成一些文本行,然后通过perl中的循环对其进行模式检查.
would use cat to generate some lines of text that would then be checked for the pattern by the loop in perl.
所以您看到,while(<>)为您提供了非常标准的UNIX命令行行为...处理我提供给您的所有文件,或处理我通过管道传递给您的内容.
So you see, while(<>) gets you a very standard UNIX command line behavior...process all of the files I give you, or process the thing I piped to you.
这篇关于<>的用途是什么在Perl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!