2012-02-09 38 views
3

我有一个subrouting输出FQDN的列表,以换行分隔:Perl:子程序输出;输入foreach语句

x1.server.com 
s2.sys.com 
5a.fdsf.com 

^^它在这种格式,所以没有比{变量文本} {可变文本等模式。 }。{可变文本}

我的问题是如何将我能够得到这个输出作为foreach语句,这样我可以通过每个迭代FQDN的输入?

回答

6

注意:你说子输出一个列表,但我假设你的意思是它输出一个字符串。否则,这个问题是没有意义的。

就劈在新行输出。假设调用子程序​​:

for my $fqdn (split /\n/, subname()) 

布赖恩·罗奇在评论中指出,最佳的解决方案是使例程返回一个列表,而不是一个字符串。但是,这对您而言可能不是一个可行的解决方案。无论哪种方式,如果您想尝试,只需在子例程的相应位置添加split即可。例如:

sub foo { 
    ... 
    #return $string; 
    return split /\n/, string; 
} 

如果你想获得先进的,你可以利用wantarray功能,可检测其背景则子程序调用的:

sub foo { 
    ... 
    return $string unless wantarray; 
    return split /\n/, string; 
} 

虽然这是很可爱的,它可以导致不必要的行为,除非你知道你在做什么。

+3

+1或...更改子程序以实际返回数组而不是字符串。 – 2012-02-09 19:38:33

+1

@BrianRoach这对于这种情况来说是最佳的,但可能是因为它在其他地方被使用,他不能改变子程序。 – TLP 2012-02-09 19:41:11

+1

@TLP - 谢谢你,我会接受你的回答。 @Brian Roach:我最终真正接受了你的建议。我添加了'push @ results,$ domain',然后'return @ results'到他们的子程序的相关部分,然后像'foreach $ host(get_mirror_list()){'''调用'foreach'循环,并且它运行得非常好。我不是perl的专家,所以我可以得到的任何专家建议我尝试实现,而不是简单的方法,尽管这样做似乎更容易。谢谢! – drewrockshard 2012-02-09 19:59:27

1
my $data = mySubRoutine() 
# Data now contains one FQDN per line 

foreach (my $line = split(/\n/,$data)) 
{ 
    doStuffWith($line); 
} 
0

我不知道你是否真的意味着你的子程序“输出”一个列表 - 即它将列表打印到标准输出。你有这样的事吗?

#!/usr/bin/perl 

use strict; 
use warnings; 
use 5.010; 

sub print_list_of_fqdns { 
    say "x1.server.com\ns2.sys.com\n5a.fdsf.com"; 
} 

print_list_of_fqdns(); 

如果是这样的话,那么你需要有点聪明并重新打开STDOUT到一个变量。

#!/usr/bin/perl 

use strict; 
use warnings; 
use 5.010; 

sub print_list_of_fqdns { 
    say "x1.server.com\ns2.sys.com\n5a.fdsf.com"; 
} 

sub get_list_of_fqdns { 
    # Declare a buffer 
    my $string; 

    # Open a filehandle that writes to the buffer 
    open my $fh, '>', \$string or die $!; 

    # Set your new filehandle to the default output filehandle 
    # (taking a copy of the original one) 
    my $old_fh = select $fh; 

    # Call the function. This will now write the list to the 
    # variable $string instead of STDOUT 
    print_list_of_fqdns(); 

    # Split $string to get the individual FQDNs 
    my @fqdns = split /\n/, $string; 

    # Replace the old default output filehandle 
    select $old_fh; 

    # Return the list of FQDNs 
    return @fqdns; 
} 

say join '/', get_list_of_fqdns();