-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi all,
I am a perl newbie, who is learning perl because I accidentally became a 
sysadmin at work (sigh). My first task was a set of perl scripts to change 
entries in .hosts files for BIND/DNS. The first one I wrote only needed to 
change the TTL value in the file, and so I kinda munged it by using, in part:

    if ($line=~/\)$/) {
      print FILEOUT "                        $ttl )\n";

Now I need to write one that will update the IP address, wherever it is 
given. Assuming that I have two variables $IPold and $IPnew, how would I 
write a regex to replace the one above that will find all instances of $IPold 
in a variable $line, and replace them with $IPnew? 

Here is some more code to put it in context:

#!/usr/bin/perl

use strict

my $dir= shift || '.';  # work only in the dir it is called from

print "--==++ Update MX records ++==--\n";
print "Enter old IP: ";
my $IP1=<STDIN>;
print "Enter new IP: ";
my $IP2=<STDIN>;
chomp $IP1;             # remove newline chars
chomp $IP2;             # remove newline chars

opendir(DIR, $dir) or die "Cannot open $dir for reading: $!\n";
for my $file (grep(!/^\.\.?$/, readdir(DIR))) {
  chomp $file;
  next unless ($file =~ /\.hosts$/);

  open (FILEOUT, ">$dir/${file}.jonnew") or die "Cannot open 
$dir/${file}.jonnew for writing: $!\n";
  open (FILEIN, "$dir/$file") or die "Cannot open $dir/$file for reading: 
$!\n";

  my $changed = 0;

  while (my $line = <FILEIN>) {
    chomp ($line);
    $line =~ s/\r$//;

    if ($line=~/mail            IN      A       $IP1/) {
      print FILEOUT "mail            IN      A       $IP2\n";
      $changed++;
    } else {
      print FILEOUT "$line\n";
    }
  }

  close (FILEIN);
  close (FILEOUT);

  if ($changed) {
    unlink("$dir/$file");
    link("$dir/${file}.jonnew", "$dir/$file");
    unlink("$dir/${file}.jonnew");
  } else {
    unlink("$dir/${file}.jonnew");
  }

}
closedir(DIR);



- -- 
Jon Tillman
http://www.eruditum.org

The worst thing about censorship is

-----BEGIN PGP SIGNATURE-----
Version: PGP 6.5.1i

iQA/AwUBOuMfOdga7tZtnIOtEQJmGACeKOS2ToMo5WM/ovxtaIRKBZ7/sikAn1/9
DMlkVxE1ITApG/6sco4yUBHn
=v21C
-----END PGP SIGNATURE-----

Reply via email to