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

Unable to replace text in a file using perl

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

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. 您在第 19 行 $tempfile = "D:/PATH/temp.txt"; 的末尾缺少 ;
  2. 您没有打开 MYFILE 进行阅读,所以您应该先打开它,然后关闭该文件处理程序

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

    开头

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

  4. 记住在处理完文件后始终关闭文件处理程序,否则有时您的数据不会从缓冲区中刷新。