By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,691 Members | 1,997 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,691 IT Pros & Developers. It's quick & easy.

how 2 edit file like list of lines :

P: 51
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 :
Expand|Select|Wrap|Line Numbers
  1.    sub read_line { 
  2.       my $filename = shift; 
  3.       my $index    = shift; 
  4.       open FILE, $filename or die "can't open $filename";
  5.       my @text = <FILE>;
  6.       return $text[$index];
  7.    }
  8.  
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).
Expand|Select|Wrap|Line Numbers
  1. sub write_line { 
  2.    my $filename = shift; 
  3.    my $index    = shift; 
  4.    my $text     = shift;
  5.    open FILE, $filename or die "can't open $filename";
  6.    my @file = <FILE>;   
  7.  
  8.    @file = (@file[0..($index-1)],"$text\n",@file[$index..$#file]);
  9.    print @file;
  10. }
  11.  
my question is whether there's a better way of doing these simple commands ?

thanks
Sep 27 '09 #1
Share this Question
Share on Google+
4 Replies


numberwhun
Expert Mod 2.5K+
P: 3,503
@zcabeli
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
Sep 27 '09 #2

Expert
P: 70
Consider using the http://perldoc.perl.org/Tie/File.html core module.
It allows you to perform array operations on lines of a file without having
to load the entire file into memory.
Sep 27 '09 #3

P: 51
thanks for the help !
the tie package really suits my requirements.
btw, sorry for not following the guidelines this time, i'll make sure it won't happen again.
Sep 29 '09 #4

numberwhun
Expert Mod 2.5K+
P: 3,503
@zcabeli
Much appreciated! :)
Sep 29 '09 #5

Post your reply

Sign in to post your reply or Sign up for a free account.