in reply to Re: Opening a file for reading or writing (was: Newbie)
in thread Opening a file for reading or writing (was: Newbie)

I'm a little bit confused.
I want to read the file but also modify the file if it matches with '
so can I just open(FILE, "height.txt");
I tried everything, but it still doesn't do anything.
my data in the text file I load stay the same.
  • Comment on Re: Re: Opening a file for reading or writing (was: Newbie)

Replies are listed 'Best First'.
Re: Re: Re: Opening a file for reading or writing (was: Newbie)
by Corion (Patriarch) on Mar 18, 2001 at 01:32 UTC

    Inplace modification of text files is considered harmful. I suggest that you write your output first to a second file and then rename the first file to a backup filename and the second file then to the original filename.

    If you are bent on modifying a file in place (which is a bad idea while developing a program), just take a look at the documentation for the open() call :

    open(DBASE, '+<$file') # open for update or die "Can't open '$file' for update: $!";

    But I really really really have to recommend that you let your script output the stuff to the console first, and then simply redirect the console output into a new file. This is much much safer, and Perl has the -i command line switch which lets you switch on the in place modification easily.

Re: Re: Re: Opening a file for reading or writing (was: Newbie)
by premchai21 (Curate) on Mar 18, 2001 at 01:47 UTC

    Try this: perl -i.bak -pe "s/\'/\t/;" somefile.dat

    The entire problem can be solved with a one-liner. Using tr or y instead of s might be good in this case because s loses performance due to regex computation. You don't really need a regex here -- you're only replacing one character -- unless, of course, you only want to replace the first one, in which case use s.

    Modifying a file, then putting the modified file in place of the original file, is known as modifying the file "in place", which is done using the i switch. The .bak is to make a backup as somefile.dat.bak, so that in case of error, you can recover the original data. Since you are modifying it in place, your while(<FILE>) { ... } loop becomes a while(<>) { ... } loop. To get the modified data to be output back to the file, you need to use a print statement, thus: while(<>) { ... print; } This can be accomplished by using the p switch, which places that around whatever code is given. Finally, the resulting code is so short that it can be one-lined using e, which is "run code from next argument".

    See perlman:perlrun and perlman:perlop for more information on perl options and operators.

    Drake Wilson

    Update: D'oh! Corion had already pointed out -i. Oh well.