Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Remove multiple lines in file if pattern found based on array element, in perl

by wrog (Friar)
on Nov 06, 2014 at 23:59 UTC ( [id://1106440]=note: print w/replies, xml ) Need Help??


in reply to Remove multiple lines in file if pattern found based on array element, in perl

  1. Learn to indent; your code is almost completely unreadable.

  2. There is only one file pointer that keeps track of where you are in the file, so by the time you've read over something and decided whether you want to keep it or not, you've already passed it and you'd need to use seek to move the pointer back to the start of it (if, say, you wanted to overwrite it because you're not keeping it), except that

  3. You're using buffered IO (<> and print) rather than sysread and syswrite, which means that what you've read may have nothing to do with where the file pointer actually is. When reading, the file pointer will keep moving forward to fill up the buffer and <> returns what's in the buffer to you one line at a time; when you switch to writing, assuming you're not using one of the modes that moves the pointer just because you switched (e.g., +>>), the pointer could be anywhere up to a buffer's worth further forward than you think it is -- and since you don't know how large the buffer is, that means basically anywhere -- and thus you're just randomly scrambling things when you write.

  4. There is really no way to edit a text file in place. In particular, there is no way to delete stuff from the middle of a file in place; you'd have to copy over everything that comes afterwards to fill in the space, at which point you may as well be rewriting the file anyway. The only cases where this actually works well is if you have a file consisting entirely of fixed-length records where you can just "black out" a particular stretch (i.e., there's something in your format that can say a record has been deleted, or maybe copy in a record from the end of the file, thus shortening it, if the order of the records doesn't matter), but then this won't be a text file anymore and also, you'd have to use seek and syswrite to do this properly.

  5. The code you've written is already pretty much as if you're copying the file anyway; it looks to me like if you change all of your print statements so that you're writing to a different file, then unlink the original file, and rename the new one, chances are it'll do what you want.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2024-04-25 22:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found