Hello Friends,

I am learning Perl now. I have a small query.

I have a directory Z with file name Z.txt.
I would like to copy this file Z.txt to 3 new dir with new filenames
as follows
dir 1 1.txt
dir 2 2.txt
dir 3 3.txt

I would like to then open 1.txt from dir 1 and edit the first 4 lines.

For eg: I have a line as follows in the text.
x y Z
10 11 12

I need to change it as folows

x y z

13 14 15

I need to do the same for all the 3 files.

I have tried the following and I guess there is a much shorter way to
do this

open FILE, "z.txt" or die $!;
while (<FILE>) {
print $_;
mkdir("1", 0777) || print $!;
copy("z.txt" ,"1.txt") or die "Copy failed: $!";
move("1.txt" ,"/home/privat/ temp/PerlWD/ 1");
mkdir("2", 0777) || print $!;
copy("z.txt" ,"2.txt") or die "Copy failed: $!";
move("2.txt" ,"/home/privat/ temp/PerlWD/ 2");
mkdir("3", 0777) || print $!;
copy("z.txt" ,"3.txt") or die "Copy failed: $!";
move("3.txt" ,"/home/privat/ temp/PerlWD/ 3");
print " -Done";

I am not sure how to edit the file and then save it in the respective
file name.

Looking forward to your response.


10 Years
Discussion Span
Last Post by dwks

Hi Kevin,

Ho w do I simplify my problem. I went through file management chapters and found only the commands used above. Any hints would be helpful.


You can read from and write to the same file at once, but it's difficult.

You're best off creating a copy of the file and modifying that, then replacing the original file with the modified one, as you've done.

You could definitely simplify the code by creating a function which will handle any filename, though.


You can read from and write to the same file at once, but it's difficult.

Actually it is very simple, you can use the Tie::File module to read/write to the same file or perls inplace editor, which would be my choice since it is way more effcient than Tie::File, but Tie::File has an extremely easy interface.


Correction: it's difficult in C and C++, but of course Perl would have a module for it. ;) It looks like a very useful one, too . . . .

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.