while (my $line = ){ $line =~ s/[^\\]#.*//; $line =~ s/^#.*//; $line =~ s/\\#/#/g; print "$line"; } #### \#Not a comment #Comment \#Not a comment #But this is a comment arbitrary text #Comment arbitrary text \#Not a comment arbitrary text \#Not a comment #But this is a comment arbitrary text #Comment \#This is part of the comment #### #Not a comment #Not a comment arbitrary text arbitrary text #Not a comment arbitrary text #Not a comment arbitrary text