收录日期:2021/01/23 05:57:29 时间:2010-03-31 11:07:01 标签:perl

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" }.)