2012-05-20 12 views
2

昨天我寫了一個小程序來解析我的/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?如果我不寫它,請回到整個行。變量是否會評估其價值?

回答

8

map的列表上下文結果是評估每個匹配主機的塊的所有結果的串聯。請記住,塊的返回值是最後一個表達式的值,無論您的代碼是否包含明確的return。沒有最後的$name,最後一個表達式—,因此塊’的返回值—是split的結果。

另一種方式來寫它是

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

你可以融合mapgrep得到

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

也就是說,如果給定主機符合您的條件,則將其分解。否則,該主機沒有結果。