Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Andrzejek on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to search and replace in an open file? 2

Status
Not open for further replies.

Smileyq

ISP
Feb 25, 2000
4
US
I'm having trouble writing a program for dns modifications. I need to find a way to search an open file and change or substitute the found results with the input.
Example---->
sub modify_dns {
open DNS, "/var/named/domain.com.hosts";
(need to search and replace here)
Any help woudl be great apprecaited. Thanks ahead of time
 
first read in the contents of the file. you could either have an array with one line per entry, or you could have it all in a single string. then search through and do the replacements, then write it back into the file. here's basically how that would look:[tt]
sub whatever
{
open FILE, &quot;<file.ext&quot; or die &quot;file failed: $!&quot;;
my $file = join '', <FILE>;
close FILE;
$file =~ s/search/replace/g;
open FILE, &quot;>file.ext&quot; or die &quot;file failed: $!&quot;;
print FILE $file;
close FILE;
}
[/tt]
if you want to do the array variation, read the file in like this, 'my @file = <FILE>;', and that'll fill it in.
is this enough? &quot;If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito.&quot;
 
I'm going to give this a whirl and see how it works out. Thanks so much for the help. I'll let you know.
 
I'm getting this error with the join command
Not enough arguments for join at F_replace line 44, near &quot;join,&quot;
Execution of F_replace aborted due to compilation errors.

here is the sub of my script--> Whats up with it?


sub modify_name { open NAME, &quot;<names&quot; or die &quot;file failed: $!&quot;; my $file = join, <NAME>; close NAME; $file =~ s/$name/$replace/g; open NAME, &quot;>names&quot; or die &quot;file failed: $!&quot;; print NAME $file; close NAME} #sub
Thanks.!!1
 
it should be:[tt]
my $file = join &quot;&quot;, <NAME>;
[/tt] &quot;If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito.&quot;
 
While this does work it adds a space in front of the words everytime you run it which if run multiple times willl cause a problem.
 
It shouldn't be adding spaces, unless maybe you have a space between the quotes in the join command? Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top