<> 有什么用?在 Perl 中? [英] What's the use of <> in Perl?

查看:33
本文介绍了<> 有什么用?在 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 *.

所以,如果 shell 给你一堆文件名,而你想依次查看每个人的数据,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).

这是一个穷人的grep:

Here is a poor man's grep:

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.

这篇关于&lt;&gt; 有什么用?在 Perl 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆