我正在用 perl 编写一个脚本,我正在创建一个文件并从用户那里获取文件输入,但是当我将该文件复制到其他位置时,该文件正在复制,但它只是空的。我的代码是
# !/usr/bin/perl -w
for($i = 1;$i<5;$i++)
{
open(file1,"</u/man/fr$i.txt");
print "Enter text for file $i";
$txt = <STDIN>;
print file1 $txt;
open(file2,">/u/man/result/fr$i.txt");
while(<file1>)
{
print file2 $_;
}
close(file1);
close(file2);
}
fr1 到 fr4 正在创建,但它们是空的。就像当我运行我的代码时它要求输入我提供输入和代码运行没有错误但文件仍然是空的。请帮忙。 在第 4 行,我将 < 更改为 >,因为我想创建新文件可能需要它,但它仍然无法正常工作
最佳答案
您需要关闭写入的文件句柄才能读取该文件。
use warnings;
use strict;
use feature 'say';
for my $i (1..4)
{
my $file = "file_$i.txt";
open my $fh, '>', $file or die "Can't open $file: $!";
say $fh "Written to $file";
# Opening the same filehandle first *closes* it if already open
open $fh, '<', $file or die "Can't open $file: $!";
my $copy = "copy_$i.txt";
open my $fh_cp, '>', $copy or die "Can't open $copy: $!";
while (<$fh>) {
print $fh_cp $_;
}
close $fh_cp; # in case of early errors in later iterations
close $fh;
}
这会创建四个文件,file_1.txt
等,以及它们的副本,copy_1.txt
等。
请注意强制 检查打开
是否有效。
关于Perl-将文件从一个位置复制到另一个位置但内容不复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46600298/