【问题标题】:How does split inside map work?地图内部分割如何工作?
【发布时间】:2012-05-20 11:36:46
【问题描述】:

昨天我写了一个小子程序来解析我的 /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;
}

我将其称为 getnames('foo','/etc/hosts') 并取回与 mgmt.foo 正则表达式匹配的主机名。

问题是,为什么我必须在map 表达式中单独写$name?如果我不写它,请收回整行。变量是否计算出它的值?

【问题讨论】:

    标签: perl map split


    【解决方案1】:

    map 的列表上下文结果是对每个匹配主机评估块的所有结果的串联。请记住,块的返回值是最后评估的表达式的值,无论您的代码是否使用显式的return。如果没有最后的$name,最后一个表达式——以及块的返回值——是split的结果。

    另一种写法是

    my @hosts = map {(split)[1]} grep {/$criteria/} @allhosts;
    

    你可以融合mapgrep来得到

    my @hosts = map { /$criteria/ ? (split)[1] : () } @allhosts;
    

    也就是说,如果给定的主机符合您的条件,则将其拆分。否则,该主机没有结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      • 2020-02-10
      相关资源
      最近更新 更多