#!/usr/bin/perl use strict; use warnings; my @hosts = ("10.10.1.2 # some comment ...\n", "#10.10.1.56\n", "14.1.2.89\n"); my $pattern = '10.10.1'; foreach my $line (@hosts) { if ( my ($comment, $rest) = $line =~ /^(#)?($pattern.*\n)/) { if (defined $comment) { $line = $rest; # delete the beginning # comment char } else { $line = "#$rest"; # add a beginning # comment char } } } print @hosts; __END__ #10.10.1.2 # some comment ... 10.10.1.56 14.1.2.89