Quote:
Originally Posted by zcabeli
Hi, i'd like to have an easy way of doing IO operation in files :
my main 2 tasks are :
1. reading line from file. for this i've created the following function :
-
sub read_line {
-
my $filename = shift;
-
my $index = shift;
-
open FILE, $filename or die "can't open $filename";
-
my @text = <FILE>;
-
return $text[$index];
-
}
-
2. writing a text in specific line : in this part i'm having some difficulties to find the optimal way of implementation. i can do that by reading the whole file into list (as in the previous function), adding the requested line to that list, and overriding the original file with the revised list (see below).
-
sub write_line {
-
my $filename = shift;
-
my $index = shift;
-
my $text = shift;
-
open FILE, $filename or die "can't open $filename";
-
my @file = <FILE>;
-
-
@file = (@file[0..($index-1)],"$text\n",@file[$index..$#file]);
-
print @file;
-
}
-
my question is whether there's a better way of doing these simple commands ?
thanks
Before I get to your question I am going to say that having 44 posts under your belt, you are more than expected to know how to use code tags. I have corrected your post, but I think you need to please re-read the
posting guidelines and use them correctly next time. If not, you will start accruing infractions.
As for your question, I would suggest that you write the new file information out to a temp file, that way you can verify it is doing its job correctly. You need to make sure you open that temp file for writing as well.
As for replacing the line, why not use a regex to find the line you want to replace and write out to the temp file the new line, when that line in question is found. And, if not, the lines pass through the test and get written out to file.
Regards,
Jeff