Perl-将文件从一个位置复制到另一个位置但内容不复制

标签 perl

我正在用 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/

相关文章:

linux - 守护进程 MCE 进程的状态影响父进程

perl - 无法在 ~/modules/Log/Syslog/Constants.pm 第 28 行使用未定义的值作为 ARRAY 引用

perl - 为什么在使用 `do` 函数时无法加载 Perl 库?

linux - 如何通过SSH成为 super 用户

perl - Sqlite 无法使用 Mojolicious 和 Par Packer 找到数据库文件

python - 将 Perl 翻译成 Python

perl - 排序多级 Perl 散列(基于算术动态)

regex - 如何验证用户输入中的 Perl 正则表达式?

arrays - 从二维数组 perl 创建 CSV 文件

apache - 如何在可以通过 ssh 连接的服务器上打开 Web 浏览器?