在Perl中,以编程方式从标准输入或输入文件(如果提供)读取最流畅的方法是什么?
while (<>) {
print;
}
如果没有指定文件,则从标准输入读取,否则将从命令行指定的文件中读取。
如果您需要在命令行中使用此循环结构,则可以使用-n
选项:
$ perl -ne 'print;'
在这里,你只需将第一个示例中的代码放在第二个示例中的''
之间即可。
这提供了一个可操作的命名变量:
foreach my $line ( <STDIN> ) {
chomp( $line );
print "$line\n";
}
要读取一个文件,可以像这样将其输入到管道中:
program.pl < inputfile
foreach my $line ( <STDIN> ) {
。 - tiktakwhile(my $line = <>) { print $line; }
。 - MikeKullswhile (my $line = <>, defined $line) { ... }
或者 while (<>) { my $line = $_; }
,以避免在空白行处停止。请注意,这两种写法不会改变原来的意思。 - Greg Nisbetwhile (<>) {
print $_; # or simply "print;"
}
这可以被压缩为:
print while (<>);
任意文件:
open my $F, "<file.txt" or die $!;
while (<$F>) {
print $_;
}
close $F;
-n
开关。它会隐式地将你的代码包装在一个while(<>)
循环中,并灵活处理输入。#!/usr/bin/perl -n在命令行中:
BEGIN: { # 在此执行一次操作 }
# 实现单行输入逻辑 print $result;
chmod +x slickestWay.pl
现在,根据您的输入执行以下操作之一:
等待用户输入
./slickestWay.pl
从参数中命名的文件中读取(无需重定向)
./slickestWay.pl input.txt
./slickestWay.pl input.txt moreInput.txt
使用管道
someOtherScript | ./slickestWay.pl
如果您需要初始化某种面向对象接口(例如Text::CSV或类似的接口),则BEGIN
块是必要的,您可以使用-M
将其添加到shebang中。
-l
和-p
也是您的好朋友。
$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]
替换为其他变量。这种方法可以在其他答案失败时使用。 - Matija Nalisunshift
到@ARGV
中并使用钻石操作符<>
。 - David MertensDo
$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
? - David Mertensif(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
。 - Dave Sherohmanshift
在这里的作用。 - Eugen Konkov
@ARGV ="/path/to/some/file.ext";
,它就可以读取文件——因此你甚至可以在特定条件下编程默认文件。 - Axemanperl -n -e '$_ = uc($_); print;' yourfile
。使用-p选项而不是-n,Perl会自动在末尾打印$_。 - mivkmy @slurp = <>; foreach my $line (@slurp) { ... }
- David Tonhoferwhile (my $line = <>) {...
? - David Mertens