in reply to update winxp hosts file with new IP address

You need to define what you mean by your default IP address. Essentially the hosts file on Win32 typically contains just an entry for localhost. If this is all you have, plus another IP then all you need to do is overwrite the old hosts file with new data, rather than mess around with finding one IP and replacing it.

my $hosts = "C:/windows/system32/drivers/etc/hosts"; print "Line to add to hosts (x.x.x.x domain.com): "; my $line = <STDIN>; rename( $hosts, "$hosts.old" ); # effectively make backup open FILE, ">$hosts" or die "Can't write $hosts $!\n"; print FILE "127.0.0.1 localhost\n$line"; close FILE;

If you actually want to find a line and replace it the approach is a little different.

my $hosts = "C:/windows/system32/drivers/etc/hosts"; print "Line to add to hosts (x.x.x.x domain.com): "; my $line = <STDIN>; print "IP to replace: "; chomp( my $ip = <STDIN> ); rename( $hosts, "$hosts.old" ); open IN, "$hosts.old" or die "Can't read $hosts.old $!\n"; open OUT, ">$hosts" or die "Can't write $hosts $!\n"; while (my $old = <IN>) { print OUT $old unless $old =~ m/\Q$ip/; } print OUT $line; # add the new record close IN; close OUT;

If you just want to change the IP then you need to get the old ip and new ip in like at the start (remember to chomp input to remove newline). Within the loop you would just do:

$old =~ s/\Q$old_ip\s+/$new_ip /; print OUT $old;

and drop the print after the loop.

You can do it in a one liner. This particular syntax can come in very handy:

C:\>perl -pi.bak -e "s/this/that/g" <file>

This makes a backup called file.bak and replaces all instances of this with that in the original