0

我有一个脚本,它以询问用户文件名开始。我想添加一个功能,以便我可以在运行程序之前在命令行中提供文件名。

直截了当:如果我使用“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,然后它会继续请求文件。

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

4

2 回答 2

2

尝试使用数组@ARGV

  $x1 = $ARGV[0] || 'NONE';
于 2013-10-30T19:29:29.707 回答
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";
        }

    }
}
~
于 2013-10-31T11:14:51.710 回答