你如何从终端呼叫用户输入

时间:2013-10-30 19:25:11

标签: perl input

我有一个脚本,首先要求用户输入文件名。 我想添加一个功能,这样我甚至可以在运行程序之前在命令行中提供文件名。

要点: 如果我用“perl wordcounter.pl text.txt”启动我的程序, 我如何从代码中访问程序名称后面的字符串(即text.txt)?

我开始做类似的事情:

$filename = "Filename supplied in the commandline";
if ($filename == 0) {
    print "Word frequancy counter.\nEnter the name of the file that you wish to analyze.\n";
    chomp ($filename = <STDIN>); 
}

基本上如果命令行没有提供文本文件,$ filename仍然为0,然后它会继续请求文件。

任何人都知道如何在代码中访问“命令行中提供的文件名”?

2 个答案:

答案 0 :(得分:2)

尝试使用数组@ARGV

  $x1 = $ARGV[0] || 'NONE';

答案 1 :(得分:1)

虽然@ARGV是一个很有前途的选择,但我宁愿使用getopts 这是可以根据您的需要使用的示例代码

尝试此 perl sample.pl -file text.txt ,并再次无文件参数 perl sample.pl

#!/usr/bin/perl
use Getopt::Long;

# setup my defaults

GetOptions(
    'file=s'    => \$file,
    'help!'     => \$help,
) or die "Incorrect usage!\n";

if( $help ) {
    print "Common on, it's really not that hard.\n";
} else {
    print "reading the $name.\n";
    if ( -e $file ){
        open( DATA ,'<',$file ) or die "unable to open \$file = $file\n";
        while (<DATA>){
            print "$_\n";
        }
    } else {
        chomp ($file = <STDIN>);
        open( DATA ,'<',$file ) or die "unable to open \$file = $file\n";
        while (<DATA>){
            print "$_\n";
        }

    }
}
~
相关问题