in reply to Apache IP-Autoupdater

Relying on a paticular line to be at a particular position in a data file is a bad thing. Never trust hard-coded values.

I was playing around and came up with this little snippet to find out what line the ServerName directive is located on in the httpd.conf file, as well as it's value:


use strict;

open (FILE, 'httpd.conf') or die "Painfully";
my @a = <FILE>;
close FILE;

my $line_no;
my $name;

for (0..$#a) {
    if ($a$_ =~ /^ServerName\s+(.+)\s*$/) {
        $line_no = $_ + 1;
        $name = $1;
        last;
    }
}

print "Line = $line_no\nName = $name\n";

I am sure this can be condensed elegantly, I tried it with grep, but couldn't get it to work. I am sure someone in the Monastery will improve this, especially my lazy use of .+ (if Dot Star is dead, can we still use Dot Plus?)

Jeff


L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
F--F--F--F--F--F--F--F--
(the triplet paradiddle)

Replies are listed 'Best First'.
Re: Re: Apache IP-Autoupdater
by btrott (Parson) on Dec 07, 2000 at 00:16 UTC
    How about this?
    @ARGV = ('httpd.conf'); while (<>) { print("Line = $.\nName = $1\n"), last if /^ServerName\s+(\S+)\s*$/; }
    This could be reduced to a one-liner:
    % perl -ne 'print("Line=$.\nName=$1\n"), last if /^ServerName\s+(\ +S+)\s*$/;' httpd.conf
    Bit long though.