use strict; open(my $In, '<', "C:/Windows/System32/drivers/etc/hosts") or die $!; my @Output = <$In>; map{if($_ =~ /^(#)?(10\.10\.1\.2.*)/){$_ = $1 eq '#' ? $2 : "#$2";}} @Output; close $In; open(Out, '>', "C:/Windows/System32/drivers/etc/hosts") or die $!; print Out @Output;