2014-03-05 154 views
2

我有以下一串代碼:字符串比較似乎無效

my $f1 = $ARGV[0] // ''; 
my $f2 = $ARGV[1] // ''; 
print "f1: $f1\n"; 
print "f2: $f2\n"; 
if ($f2 eq '') { 
    print "reach here\n"; 
    open(DATA1, $f1) or die $!; 
} else { 
    open(DATA1, $f2) or die $!; 
} 

會收到命令行1個或2個參數,命令行調用是這樣的:

perl perl_unix_wc.pl -l file.txt 

或該:

perl perl_unix_wc.pl file.txt 

我試圖界定2個定標器以從命令線接收字符串,是否適用於情況1,那麼 '打開(DATA1,$ f2)或死掉$!'將被調用,否則'打開(DATA1,$ f1)或死亡$!'會叫。但實際上,只有情況2被執行,情況1從未到達。我的代碼在這裏有什麼問題?這裏的字符串比較有問題嗎?謝謝。

+0

你們是不是要進入的第一個參數或「」在F1和第二個參數或「」我n f2?如果你嘗試||代替 // ? –

回答

1

由於看來你不需要-l,只是pop最後一個(或唯一的)關閉的@ARGV元素,因爲在這兩種情況下,這將是該文件的名稱:

use strict; 
use warnings; 

@ARGV or die "No arguments passed to $0!\n"; 

my $file = pop; 
open my $DATA1, '<', $file or die "Unable to open $file: $!"; 

... 

但是,如果你只是要通過文件名,你可以做到以下幾點:

use strict; 
use warnings; 

while(<>){ 
    # process the file's lines 
} 
+0

我認爲我的解決方案的作品,因爲當我只傳遞1參數,'到達這裏'將被打印,但似乎文件沒有打開(該文件是在那裏,並在同一目錄中)。 – photosynthesis

+0

@photosynthesis - 如果你只是要傳遞文件名,讓Perl處理文件I/O。查看更新後的答案。 – Kenosis

1

@ARGV會返回no。的參數傳遞......如果@ARGV == 1,則執行情況1,或者如果@ARGV == 2執行情況2

#!/usr/local/bin/perl 
my $f1 = $ARGV[0] ; 
my $f2 = $ARGV[1] ; 
print "f1: $f1\n"; 
print "f2: $f2\n"; 
if (@ARGV == 1) { 
    open(DATA1, $f1) or die $!; 
} elsif (@ARGV == 2) { 
    open(DATA1, $f2) or die $!; 
} 

如果你要堅持你的編碼風格..嘗試

my $f1 = $ARGV[0] || ''; 
my $f2 = $ARGV[1] || ''; 
print "f1: $f1\n"; 
print "f2: $f2\n"; 
if ($f2 eq '') { 
    open(DATA1, $f1) or die $!; 
} else { 
    open(DATA1, $f2) or die $!; 
} 
2

使用Getopt::Long來處理命令行選項。

use Getopt::Long; # GetOptions 

use strict; 
use warnings; 
use autodie; 

GetOptions(
    'l' => \my $opt_l, 
); 

my $file = shift or die "Filename required"; 

open my $fh, '<', $file; 

if ($opt_l) { 
    print "do -l stuff\n"; 
}