Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Im tring to make my own Update, Delete and Insert subs to modify a tab deliminated file. I am also using the inplace edit to increase efficiency. Updating and deleting is a simple case of using a regex to search and replace a line, but inserting a line using the same method is proving tricky if the file is empty to start with.

The while(<>) will only run if there's lines already in the file to loop through, so thats no gud. You could check if the files empty -z and do something different in that case, but it ends up being messy.

Heres the start of my plan for inserting a line

my $line = "desc\tdate\tdetails"; # This will be the newline @ARGV = "file.tab"; # Init input file $^I = ".bak"; # Inplace editing with a bak up file if (-z "file.tab") { # somehow set the file up with a fake line to chew on ??? } while (<>) { # if theres no more lines after if (eof(ARGV)) { # take a slice of the last line # the id number to be precise # add 1 to get the next id number for # the newline we're inserting # also put the rest of the line on the end # and piggy back the line onto the last line of the file $_ .= (split /\t/)[0] + 1 . "\t$line\n"; } print; }

If anyone can help using in-place editing to insert, or knows a fast way to do this inserting, (without resorting to assigning the file to an array first and push'in the line in) I would be very grateful.

Phil d
  • Comment on Inplace editing/ inserting a newline/modify a tab deliminated file
  • Download Code

Replies are listed 'Best First'.
Re: Inplace editing/ inserting a newline/modify a tab deliminated file
by jweed (Chaplain) on Jan 27, 2004 at 15:28 UTC
    I know that you don't want to slurp the file into an array, but this is really a perfect place to use Tie::File. Even the FAQ says so. It is much faster and memory efficient than slurping, so it isn't really "resorting to assigning the file to an array first and push'in the line in."

    HTH.


    Edited for Clarity



    Code is (almost) always untested.
    http://www.justicepoetic.net/
Re: Inplace editing/ inserting a newline/modify a tab deliminated file
by Anonymous Monk on Jan 27, 2004 at 19:19 UTC
    Am I missing something? Why don't you just append the new line to the end of the file?