1

我正在编写一个 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.

现在可能出了什么问题?

4

1 回答 1

1

也许你正在运行一个旧的 perl 版本,所以你必须使用 2 params open 版本:

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> ) {
   #...
}
于 2013-04-26T08:49:41.683 回答