我正在寫一個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.
什麼能現在是錯誤的?
你確定你正在運行的腳本?開放的句子是好的,試着在打開之前打印$ arg。 – 2013-04-26 07:40:08
嗨@MiguelPrz因爲腳本給編譯錯誤,它沒有運行,因此它也沒有打印arg。 – 2013-04-26 08:33:24
如果我評論開放行,那麼$ arg的值將打印爲:**。\ test.txt ** – 2013-04-26 08:36:25