简体   繁体   English

Perl:使用Getopt :: Long从命令行和[piped STDIN | file]中获取参数

[英]Perl: Take arguments from both command line and [piped STDIN|file], using Getopt::Long

Hi I wanted to implement both command line argument1, and either piped STDIN (through lone single dash '-') or a filename as argument2, using Getop::Long in Perl. 嗨,我想使用Perl中的Getop :: Long实现命令行自变量1,以及通过管道STDIN(通过单个单破折号'-')或文件名作为自变量2。 In perldoc it is merely mentioned a little bit "A lone dash on the command line will now be a legal option, and using it will set variable $stdio": ( https://perldoc.perl.org/Getopt/Long.html ). 在perldoc中只提到了一点“命令行上的短划线现在是合法的选择,使用它会设置变量$ stdio”:( https://perldoc.perl.org/Getopt/Long.html )。 But this is far from what I can use. 但是,这远远超出了我的使用范围。 I tried the following 我尝试了以下

#!/usr/bin/perl -w
use strict;
use Getopt::Long;
my ($se, $st);
GetOptions("se=s" => \$s, '' => \$st) or die "Usage: $0 -s <tab|space|comma>\n";
$st = <STDIN>;
print "$se\n$st\n";

However $st only returns the first line or should I use a filehandle? 但是$ st只返回第一行,还是应该使用文件句柄? Then what if the lone single dash '-' is not there and a filename is specified as argument2? 然后,如果没有单独的单破折号“-”,并且将文件名指定为arguments2怎么办? Thanks a lot, 非常感谢,

Just use <> (short for <ARGV> ) instead of <STDIN> . 只需使用<><ARGV>缩写)代替<STDIN> ARGV is a special handle that reads from STDIN if @ARGV is empty, and reads from the each of the files specified in @ARGV if it's not. ARGV是一个特殊的句柄,如果@ARGV为空,则从STDIN读取,如果不是,则从@ARGV指定的每个文件读取。

GetOptions("se=s" => \my $se)
   or die "Usage: $0 -s <tab|space|comma>\n";

my $st = <>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM