[英]Programmatically read from STDIN or input file in Perl
在stl中以編程方式從stdin或輸入文件(如果提供)中讀取的最簡單的方法是什么?
while (<>) {
print;
}
將從命令行中指定的文件或stdin讀取(如果沒有給出文件)
如果在命令行中需要此循環構造,則可以使用-n
選項:
$ perl -ne 'print;'
在這里,你只要把代碼之間{}
從第一到例如''
在第二
這提供了一個命名變量來使用:
foreach my $line ( <STDIN> ) {
chomp( $line );
print "$line\n";
}
要讀取文件,請將其管道輸入:
program.pl < inputfile
在某些情況下,“最簡單”的方法是利用-n
開關 。 它隱式地用while(<>)
循環包裝你的代碼並靈活地處理輸入。
在slickestWay.pl
:
#!/usr/bin/perl -n BEGIN: { # do something once here } # implement logic for a single line of input print $result;
在命令行:
chmod +x slickestWay.pl
現在,根據您的輸入,執行以下操作之一:
等待用戶輸入
./slickestWay.pl
從參數中命名的文件中讀取(不需要重定向)
./slickestWay.pl input.txt ./slickestWay.pl input.txt moreInput.txt
使用管道
someOtherScript | ./slickestWay.pl
如果你需要初始化某種面向對象的接口,比如Text :: CSV或其他一些,你可以使用-M
添加到shebang, BEGIN
塊是必需的。
-l
和-p
也是你的朋友。
你需要使用<>運算符:
while (<>) {
print $_; # or simply "print;"
}
哪個可以壓縮到:
print while (<>);
任意檔案:
open F, "<file.txt" or die $!;
while (<F>) {
print $_;
}
close F;
如果有一個原因你不能使用上面ennuikiller提供的簡單解決方案,那么你將不得不使用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($_);
}
做
$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問題。
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(<>);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.