【发布时间】:2011-03-09 11:51:58
【问题描述】:
在 Perl 中以编程方式从标准输入或输入文件(如果提供)读取的最巧妙方法是什么?
【问题讨论】:
在 Perl 中以编程方式从标准输入或输入文件(如果提供)读取的最巧妙方法是什么?
【问题讨论】:
while (<>) {
print;
}
将从命令行指定的文件中读取,如果没有给出文件,则从标准输入中读取
如果您需要在命令行中进行此循环构造,则可以使用-n 选项:
$ perl -ne 'print;'
在这里,您只需将第一个示例中的{} 之间的代码放入第二个示例中的''
【讨论】:
@ARGV = "/path/to/some/file.ext"; 并读取文件——因此您甚至可以在特定条件下编写默认文件。
perl -n -e '$_ = uc($_); print;' yourfile。使用 -p 而不是 -n,perl 会自动在末尾打印 $_。
my @slurp = <>; foreach my $line (@slurp) { ... }
while (my $line = <>) {... 之类的名称命名读取行?
这提供了一个可以使用的命名变量:
foreach my $line ( <STDIN> ) {
chomp( $line );
print "$line\n";
}
要读取文件,请像这样通过管道输入:
program.pl < inputfile
【讨论】:
foreach my $line ( <STDIN> ) { 我同意@MikeKulls。如果 Perl 脚本不可读,这不是 Perl 的错。程序员是罪魁祸首!
while(my $line = <>) { print $line; }。
while (my $line = <>, defined $line) { ... } 或while (<>) { my $line = $_; } 以避免停在空行上吗?
在某些情况下,“最巧妙”的方法是利用-n switch。它使用while(<>) 循环隐式包装您的代码并灵活处理输入。
在slickestWay.pl:
在命令行:
chmod +x slickestWay.pl
现在,根据您的输入执行以下操作之一:
等待用户输入
./slickestWay.pl
从参数中指定的文件读取(不需要重定向)
./slickestWay.pl input.txt
./slickestWay.pl input.txt moreInput.txt
使用管道
someOtherScript | ./slickestWay.pl
BEGIN 块是必要的,如果您需要初始化某种面向对象的接口,例如 Text::CSV 或类似的,您可以使用 -M 添加到 shebang。
-l 和 -p 也是你的朋友。
【讨论】:
你需要使用操作符:
while (<>) {
print $_; # or simply "print;"
}
可以压缩成:
print while (<>);
任意文件:
open F, "<file.txt" or die $!;
while (<F>) {
print $_;
}
close F;
【讨论】:
如果你有一个原因不能使用上面 ennukiller 提供的简单解决方案,那么你将不得不使用 Typeglobs 来操作文件句柄。这是更多的工作。此示例从$ARGV[0] 中的文件复制到$ARGV[1] 中的文件。如果未指定文件,则分别默认为STDIN 和STDOUT。
use English;
my $in;
my $out;
if ($#ARGV >= 0){
unless (open($in, "<", $ARGV[0])){
die "could not open $ARGV[0] for reading.";
}
}
else {
$in = *STDIN;
}
if ($#ARGV >= 1){
unless (open($out, ">", $ARGV[1])){
die "could not open $ARGV[1] for writing.";
}
}
else {
$out = *STDOUT;
}
while ($_ = <$in>){
$out->print($_);
}
【讨论】:
$ARGV[0] 等)所有其他答案都失败了......
unshift 转换为@ARGV 并使用菱形运算符<>。
做
$userinput = <STDIN>; #read stdin and put it in $userinput
chomp ($userinput); #cut the return / line feed character
如果你只想读一行
【讨论】:
以下是我如何制作一个可以接受命令行输入或重定向文本文件的脚本。
if ($#ARGV < 1) {
@ARGV = ();
@ARGV = <>;
chomp(@ARGV);
}
这会将文件的内容重新分配给@ARGV,从那里您只需处理@ARGV,就好像有人包含命令行选项一样。
警告
如果没有文件被重定向,程序将处于空闲状态,因为它正在等待来自 STDIN 的输入。
我还没有想出一种方法来检测文件是否被重定向以消除 STDIN 问题。
【讨论】:
$#ARGV < 1 而不是(我认为的)更清晰的@ARGV == 1?
if(my $file = shift) { # if file is specified, read from that
open(my $fh, '<', $file) or die($!);
while(my $line = <$fh>) {
print $line;
}
}
else { # otherwise, read from STDIN
print while(<>);
}
【讨论】:
<> 操作符会自动查找和读取命令行中给出的任何文件。不需要if。
shift在这里做什么