As others have said, this line,
gives me a headache.map{if($_ =~ /^(#)?(10\.10\.1\.2.*)/){$_ = $1 eq '#' ? $2 : "#$2";}} @ +Output;
Do not make the mistake of assuming that fewer lines of Perl code means more efficient or "better" code. This map is an implied foreach loop whether you want to write the source code that way or not.
I prefer to translate $1, $2, etc into named variables when possible. Compared with firing up the regex engine, this is very "cheap" CPU wise. Also, white space consumes no MIPs! Space things out and write something that you will understand 2 years from now.
Your idea of reading the hosts file into memory, my @Output = <$In>; is a good one - this file will not be "huge" and this is fine.#!/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
The idea of over-writing the original file with the modified contents is not so good. That will work most of the time, but I would make a temp file of some sort, write to that, then rename the temp file to the host file name. If for nothing else, this will help with the debugging!
There is no truly "atomic" operation on the file system - something can always go wrong within a fileop. Good system code plans for that and also makes the "window of vulnerability" as short as possible.
In reply to Re: Read in hostfile, modify, output
by Marshall
in thread Read in hostfile, modify, output
by razmeth
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |