2013-10-30 63 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"; 
     } 

    } 
} 
~