Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: updating a file

by IraTarball (Monk)
on Nov 29, 2001 at 00:21 UTC ( #128167=note: print w/replies, xml ) Need Help??


in reply to updating a file

This code 'works' for me, well, for some strange distorted definition of 'works.' I think the problem here is that you are trying to update the current like, but you've just read the current line so the write happens on the next line. What I get when I run this is a horribly garbled header file.
You could do this in a number of ways. The most straight forward would be to open one file for reading, one file for writing, and itterate through the read file, replacing the desired lines as you go.
use File::Copy; open(RFH, "<ReadFile.h") or die "Trying:$!"; open(WFH, ">WriteFile.h") or die "Trying:$!"; while(<RFH>) { s/search/replace/; print WFH; } close RFH; close WFH; move ("WriteFile.h", "ReadFile.h") or die "With a vengance:$!";
I didn't actually run this, but it should be close. You might want more descriptive diemessages.

The idiomatic way to do this would be with an 'in place edit' that does the file move for you.

$^I = '.old'; @ARGV = ("header.h"); while (<>) { s/search/replace/; print; }
This will save the old file as "header.h.old" for you.
(I did run this code) BTW: The $^I is equivalent to the '-i' switch mentioned above by broquaint

Ira,

"So... What do all these little arrows mean?"
~unknown

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://128167]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (8)
As of 2019-05-21 09:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you enjoy 3D movies?



    Results (132 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!