【问题标题】:Writing and reading of a File in a Perl program在 Perl 程序中写入和读取文件
【发布时间】:2012-10-08 04:53:46
【问题描述】:

我有一个原始文件 A.txt。 我写信给 A_Copy.txt。 我想知道在同一个程序中关闭之前和关闭之后是否可以阅读 A_Copy.txt? 我想在同一程序中使用Tie::File 修改A_Copy.txt

A -> A_Copy.txt

关闭前读取 A_Copy.txt

关闭后读取A_Copy.txt

修改 A_Copy.txt

【问题讨论】:

  • 如果你想知道文件是否可读.. 使用-rfile.. 如果你想做其他事情.. 给我们看一些代码..跨度>

标签: perl file-handling


【解决方案1】:

使用copy应该足以确保旧文件可读,而新文件可写可读,copy表现非常好。 要检查文件是否可读,最好的方法是使用 -r 使用系统统计调用

#!/usr/bin/perl

use File::Copy;
use Tie::File;

my $i = "A.txt";      # input file
my $o = "A_Copy.txt"; # output file
my @a;                # array to use with tie

copy($i, $o) or die;  

# check that the new file is readable, actually unneeded since copy
# would fail on any error
die unless (-r $o);   

# fill an array with the lines of the new file
tie @a, "Tie::File", $o or die;
# change the first line of the new file
$a[0] = "Hi";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多