繁体   English   中英

文件未在Perl中复制

[英]File not getting copied in perl

文件“ / root / actual”不会通过perl脚本覆盖“ / root / temp”的内容。 如果手动编辑,“ / root / actual”将被修改。

copy("/root/actual","/root/temp") or die "Copy failed: $!";


open(FILE, "</root/temp") || die "File not found";
my @lines = <FILE>;
close(FILE);

my @newlines;
foreach(@lines) {
   $_ =~ s/$aref1[0]/$profile_name/;
   push(@newlines,$_);
}

open(FILE, ">/root/actual") || die "File not found";
print FILE @newlines;
close(FILE);

文件“ / root / actual”不会通过perl脚本覆盖“ / root / temp”的内容。 如果手动编辑,“ / root / actual”将被修改。

您是说/root/temp不会被/root/actual取代吗? 还是正在/root/temp进行您想要的修改,但是在程序末尾没有通过/root/acutual复制?

我建议您阅读现代Perl编程实践。 您需要use warnings; use strict; 在您的程序中。 实际上,除非use strict;否则该论坛上的许多人都不会打扰回答Perl问题use strict; use warnings; 被使用。

$aref1[0]从哪里来? 我在程序的任何位置都没有看到@aref1声明。 或者,就此而言, $profile_name

如果您将整个文件读入正则表达式,则没有理由先将其复制到临时文件中。

我用更现代的语法重写了您的内容:

use strict;
use warnings;
use autodie;

use constant {
    FILE_NAME => 'test.txt',
};

my $profile_name = "bar";                #Taking a guess
my @aref1 = qw(foo ??? ??? ???);         #Taking a guess

open my $input_fh, "<", FILE_NAME;
my @lines = <$input_fh>;
close $input_fh;

for my $line ( @lines ) {
    $line =~ s/$aref1[0]/$profile_name/;
}

open my $output_fh, ">", FILE_NAME;
print ${output_fh} @lines;
close $output_fh;

这可行。

笔记:

  1. use autodie; 意味着您不必检查文件是否已打开。
  2. 当我使用for循环时,可以在数组中进行就地替换。 每一项都是指向数组中该条目的指针。
  3. 由于您还是要替换原始文件,因此无需copy或临时文件。
  4. 我没有在这里使用它,因为您没有使用它,而是在map { s/$aref1[0]/$profile_name/ } @lines; 可以将其替换for循环。 地图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM