我正在编写一个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.
现在可能出现什么问题?
答案 0 :(得分:1)
也许你正在运行一个旧的perl版本,所以你必须使用2 params open version:
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> ) {
#...
}