2013-04-26 53 views
1

我正在寫一個perl腳本,它讀取一個文本文件(其中包含多個文件的絕對路徑,一個在另一個下面),從abs路徑計算文件名&然後將由空格分隔的所有文件名追加到同一個文件中。因此,考慮的test.txt文件:在perl中打開文件給出錯誤?

D:\work\project\temp.txt 
D:\work/tests/test.abc 
C:/office/work/files.xyz 

所以運行該腳本後,同一文件將包含:

D:\work\project\temp.txt 
D:\work/tests/test.abc 
C:/office/work/files.xyz 

temp.txt test.abc files.xyz 

我有此腳本revert.pl:

use strict; 

foreach my $arg (@ARGV) 
{ 
    open my $file_handle, '>>', $arg or die "\nError trying to open the file $arg : $!"; 
    print "Opened File : $arg\n"; 
    my @lines = <$file_handle>; 
    my $all_names = ""; 

    foreach my $line (@lines) 
    { 
     my @paths = split(/\\|\//, $line); 
     my $last = @paths; 
     $last = $last - 1; 
     my $name = $paths[$last]; 
     $all_names = "$all_names $name"; 
    } 

    print $file_handle "\n\n$all_names"; 
    close $file_handle; 
} 

當我運行腳本我得到以下錯誤:

>> perl ..\revert.pl .\test.txt 
Too many arguments for open at ..\revert.pl line 5, near "$arg or" 
Execution of ..\revert.pl aborted due to compilation errors. 

這裏有什麼問題?

更新:問題是我們正在使用一個非常舊的版本的Perl。所以改變了代碼:

use strict; 

for my $arg (@ARGV) 
{ 
print "$arg\n"; 
open (FH, ">>$arg") or die "\nError trying to open the file $arg : $!"; 
print "Opened File : $arg\n"; 
my $all_names = ""; 
my $line = ""; 

for $line (<FH>) 
{ 
    print "$line\n"; 
    my @paths = split(/\\|\//, $line); 
    my $last = @paths; 
    $last = $last - 1; 
    my $name = $paths[$last]; 
    $all_names = "$all_names $name"; 
} 
print "$line\n"; 

if ($all_names == "") 
{ 
    print "Could not detect any file name.\n"; 
} 
else 
{ 
    print FH "\n\n$all_names"; 
    print "Success!\n"; 
} 
close FH; 
} 

現在,它的打印下列:

>> perl ..\revert.pl .\test.txt 
.\test.txt 
Opened File : .\test.txt 

Could not detect any file name. 

什麼能現在是錯誤的?

+0

你確定你正在運行的腳本?開放的句子是好的,試着在打開之前打印$ arg。 – 2013-04-26 07:40:08

+0

嗨@MiguelPrz因爲腳本給編譯錯誤,它沒有運行,因此它也沒有打印arg。 – 2013-04-26 08:33:24

+0

如果我評論開放行,那麼$ arg的值將打印爲:**。\ test.txt ** – 2013-04-26 08:36:25

回答

1

也許你正在運行一個老Perl版本,所以你必須使用2個PARAMS開放版本:

open(File_handle, ">>$arg") or die "\nError trying to open the file $arg : $!"; 

注意到我寫File_handle沒有$。此外,閱讀和書面方式操作,該文件將是:

@lines = <File_handle>; 
#... 
print File_handle "\n\n$all_names"; 
#... 
close File_handle; 

更新:讀取文件行:

open FH, "+>>$arg" or die "open file error: $!"; 
#... 
while($line = <FH>) { 
    #... 
} 
+0

我已經更新了這個問題。 現在它打開文件,但不能讀取行。 現在,舊版本不應該有任何問題,因爲我已經使用符合較舊版本的Perl的語法,按照這個:http://www.perl.com/pub/2000/11/begperl2.html – 2013-04-26 09:05:04

+0

顯然它只有通過讀取模式打開並且不通過寫入模式才能讀取行。覆蓋不是附加模式都不能讀取這些行。 也許perl版本太老了。 感謝您的幫助。 如果在寫入文件時遇到任何問題,將會回覆您。 – 2013-04-26 09:24:27

+0

試試這個:打開FH,「+ >> $ arg」; – 2013-04-26 09:27:11