昨天我写了一个小子程序来解析我的/ etc/hosts文件并从中获取主机名.
这是子程序:
sub getnames {
my ($faculty, $hostfile) = @_;
open my $hosts ,'<', $hostfile;
my @allhosts = <$hosts>;
my $criteria = "mgmt." . $faculty;
my @hosts = map {my ($ip, $name) = split; $name} grep {/$criteria/} @allhosts; # <-this line is the question
return @hosts;
}
Run Code Online (Sandbox Code Playgroud)
我打电话给它getnames('foo','/etc/hosts')并找回了与mgmt.foo正则表达式匹配的主机名.
问题是,为什么我必须$name在map表达式中单独写?如果我不写,请回到整行.变量是否评估其值?
列表上下文结果来自map为每个匹配主机评估块的所有结果的串联.请记住,块的返回值是最后一个表达式的值,无论您的代码是否显式return.如果没有最终结果$name,最后一个表达式 - 以及块的返回值 - 就是结果split.
写它的另一种方法是
my @hosts = map {(split)[1]} grep {/$criteria/} @allhosts;
Run Code Online (Sandbox Code Playgroud)
你可以融合map并grep得到
my @hosts = map { /$criteria/ ? (split)[1] : () } @allhosts;
Run Code Online (Sandbox Code Playgroud)
也就是说,如果给定的主机符合您的标准,则将其拆分.否则,该主机没有结果.