无法使用perl替换文件中的文本

时间:2015-01-01 08:10:07

标签: perl file-io

我的Windows系统上有一个文件目录,想要替换位于first.txt的特定文件PATH的文本。 我想要做的就是替换该文件中的文本。 这是我的代码:

use strict;
use warnings;
use File::Copy qw(copy);
opendir (DIR, "D:/PATH/");
while (my $myfile = readdir(DIR)) {
    print "got a file\n";
    print $myfile."\n";
    if($myfile =~ /first/i)
    {   print "found file\n";
        while (my $row = <MYFILE>) 
        {   print $row."\n";
        }
        my $newline;
        my $tempfile;
        my $newfile;
        $newline = "this is replaced";
        $tempfile  = "D:/PATH/temp.txt"
        open ($tmp, '>', $tempfile) or die "** can't  :( **";
        print $tmp "replaced text\n okay??";
        close $tmp;
        copy $tempfile, $myfile;
        unlink  $tempfile;
    }
}

但是我收到以下错误:

syntax error at renner.pl line 19, near "open "
Global symbol "$tmp" requires explicit package name at renner.pl line 19.
Global symbol "$tmp" requires explicit package name at renner.pl line 20.
Global symbol "$tmp" requires explicit package name at renner.pl line 21.
Execution of renner.pl aborted due to compilation errors.

我真的找不到这里的错误。

1 个答案:

答案 0 :(得分:1)

这么多语法错误!

  1. 您在第19行;
  2. 的末尾遗失了$tempfile = "D:/PATH/temp.txt";
  3. 您没有打开MYFILE进行阅读,因此您应首先打开它,然后关闭该文件处理程序

    open MYFILE, $myfile;
    while (my $row = <MYFILE>){
        print $row."\n";
    }
    close MYFILE;
    
  4. 文件处理程序名称不应以符号$

    开头

    open (tmp, '>$tempfile') or die "** can't :( **";

  5. 请记住,当您完成文件后,请务必关闭文件处理程序,否则有时您的数据不会从缓冲区刷新。