我正在编写一个 perl 脚本,它读取一个文本文件(其中包含许多文件的绝对路径,一个在另一个之下),从 abs 路径计算文件名,然后将所有用空格分隔的文件名附加到同一个文件中。因此,考虑一个 test.txt 文件:
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.
现在可能出了什么问题?