in reply to Read in hostfile, modify, output
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Read in hostfile, modify, output
by eyepopslikeamosquito (Archbishop) on Dec 17, 2016 at 22:31 UTC | |
by Marshall (Canon) on Dec 20, 2016 at 22:48 UTC | |
by Anonymous Monk on Dec 20, 2016 at 23:14 UTC | |
by Marshall (Canon) on Dec 21, 2016 at 00:41 UTC | |
by eyepopslikeamosquito (Archbishop) on Dec 21, 2016 at 19:19 UTC | |
| |
by Anonymous Monk on Dec 21, 2016 at 01:13 UTC | |
| |
by Anonymous Monk on Dec 21, 2016 at 10:27 UTC |