Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: deleting lines from file

by jweed (Chaplain)
on Mar 18, 2004 at 02:51 UTC ( [id://337593]=note: print w/replies, xml ) Need Help??


in reply to deleting lines from file

It's unclear what "newfile" should contain. If you want it to have
one 111 ury
th  ese  ll
in it, thenyour program makes absolutely no sense. Since this smells like homework, here are some questions I am asking myself, and then a proposed solution that the prof probably won't accept ;) :
  1. Why are you counting occurances or existance of the lines in oldfile? How does this advance your aims to delete a line?
  2. Why are you printing the number of times oldfile has a certain line to the standard output. This makes little sense to me.
And, to wrap it up, a solution for inplace editing (this is as per what you seem to be asking.):
#!/usr/bin/perl use strict; use warnings; use Tie::File; my $value_to_delete = <STDIN>; chomp $value_to_delete; tie my @file, 'Tie::File', "file" or die "Couldn't open: $!"; @file = grep { $_ ne $value_to_delete } @file; untie @file;
N.B. This solution is quite cost effective memory-wise, because Tie::File does some cool behind-the-scenes stuff so you don't have to read everything in at once. This is huge if the file is very large.

UPDATE: Here's a non-in place solution:
#!/usr/bin/perl -pi.orig BEGIN {$value_to_delete = <STDIN>} undef $_ if $_ eq $value_to_delete;



Code is (almost) always untested.
http://www.justicepoetic.net/

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2024-04-18 15:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found