开发者

Perl and hosts file mapping question?

I have a hosts file that looks like this:

10.10.10.1 myserver1 myserver1alias

10.10.10.2 myserver2 myserver2alias
开发者_高级运维

I'm looking for a way using perl to pass in an argument of myserver1 and have it return myserver1alias, likewise if I pass in myserver2 it should return myserver2alias. Any suggestions?


From the command line:

$ perl -lane 'print $F[-1] if $F[1] eq "myserver1"' /etc/hosts


while(<>){
 if (/myserver1/){
  @s = split /myserver1/,$_,2;
  print $s[-1];
 }
}


The quick-and-dirty way is:

perl -nE 'say $1 if /myserver1\s+(\w+)$/' path/to/hostfile

You might need to do queries similar to this from time to time, so you could probably make a reusable chunk of code to do this for you. Something like:

#!/usr/bin/perl

use strict;
use warnings;
use 5.10;

use HostFileParser;

my $host = HostFileParser->parse("path/to/hostfile")

my $server = $host->find(server => "myserver1")

say $server->alias;

Of course, I'm not going to "give you teh codez" for all of that. ;)

(These answers assume Perl 5.10, but if you don't have it the changes are just say $x => print "$x\n", or sub say { print "@_\n" }.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜