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

Re: How to delete the line I have just read?

by l.frankline (Hermit)
on Aug 04, 2008 at 14:05 UTC ( [id://702061]=note: print w/replies, xml ) Need Help??


in reply to How to delete the line I have just read?

Hi,

If I am not wrong then follow this code

my $filename = 'yourfilename.txt'; open FILE, "$filename" || die "cant open file for read"; @data = <FILE>; close FILE; for my $line (0..$#data) { # execute process method -- do your operation stuffs here. &process($data[$line]); # if you want to delete, make the line with null value; $data[$line] = ""; } $entirefile = join "\n", @data; open OUT, "outfile.txt" || die "cant open file for write"; print OUT $entirefile; close OUT;

Replies are listed 'Best First'.
Re^2: How to delete the line I have just read?
by chromatic (Archbishop) on Aug 04, 2008 at 19:40 UTC

    That code could be prettier, but it has a serious bug in it:

    # if you want to delete, make the line with null value; $data[$line] = "";

    This doesn't actually delete the line; it replaces it with an empty line. Oh, and there's another bug -- why join lines on newlines when you haven't chomped away existing newlines? Here's much better code:

    my $filename = 'yourfilename.txt'; my $newfile = 'new_filename.txt'; filter_file( $filename, $newfile ); # this line may be unnecessary depending on your filesystem unlink $filename; rename( $filename, $newfile ); sub filter_file { my ($from, $to) = @_; open my $fh, $from or die "Can't read '$from': $!\n"; open my $out_fh, '>', $to or die "Can't write '$to': $!\n"; while (<$fh>) { next if should_delete_line($_); print {$out_fh}; } }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2024-04-19 11:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found