Daanish
Daanish

Reputation: 1091

Writing and reading of a File in a Perl program

I have an original file A.txt. I write to A_Copy.txt. I want to know if I can read A_Copy.txt before closing and after closing it in the same program? I want to modify A_Copy.txt using Tie::File in the same program.

A -> A_Copy.txt

Read A_Copy.txt before closing

Read A_Copy.txt after closing

Modify A_Copy.txt

Upvotes: 0

Views: 153

Answers (1)

user1711180
user1711180

Reputation:

Using copy should be enough to be sure that the old file is readable, and the new file is writable and readable, copy performs very well. To check if a file is readable the best way is to use -r which uses the system stat call

#!/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";

Upvotes: 2

Related Questions