Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: find & replace a string in perl

by anonymized user 468275 (Curate)
on Nov 25, 2010 at 14:33 UTC ( #873648=note: print w/replies, xml ) Need Help??

in reply to find & replace a string in perl

Hmm I am not sure I understand either the question or the answers! The way I read it was you wanted to comment out all lines which have the word test in them, which would look like this (also putting the close outside the loop and creating a new file rather than appending which also seems wrong!:
#!/usr/bin/perl -w my $file_name = "test.txt"; open(INF,'./$file_name') || die "file could not open\n"; open(INFN,'>./${file_name}.new') || die "$!: ${file_name}.new\n"; my @line; while(@line = <INF>) { if ( $line =~ /test/) { print "found at $.: $line $line = "\# $line"; } print INFN $line; } close(INF); close INFN;
If you really want to append to the file, read it in, close it and then reopen it for append. Anyway, it is usually wrong to open or close the same file inside a loop.

One world, one people

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2022-08-12 02:35 GMT
Find Nodes?
    Voting Booth?

    No recent polls found