2013-10-30 62 views
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>); 
} 

基本上如果没有文本文件在命令行,$文件名供给仍然0,然后它会继续询问文件。

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

回答

2

尝试使用数组@ARGV

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

嗯测试它,和其他一些变化,没有运气。 –

+0

你会发布你如何测试它吗? – michael501

+0

@ARGV; $文件名= $ ARGV [0]; 如果($文件名== 0){ \t格格($文件名= ); } –

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"; 
     } 

    } 
} 
~