2013-05-07 73 views
0

@main::match_to_array仅输出数组@match_to_array中的最后一个元素,而不是整个数组。使用main ::打印显示其所有元素的数组变量。

我参考this SO link参考了我的代码。

输入HTML由 [email protected] [email protected] [email protected] [email protected] [email protected]

#!/usr/bin/perl –w 

use strict; 
use warnings; 
use Cwd; 

sub extractMail { 

    my $perl_path = cwd; 
    # Full HTML.htm 
    if(-e 'test.html') { 

    open(OPENFILE, "$perl_path/test.html") or die "Unable to open file"; 

    } 

    my @email = <OPENFILE>; 
    close OPENFILE; 

    foreach my $email (@email){ 

     if ($email =~ /regex to match data/{ 
     my $match = "$1\n"; 

     our @match_to_array = split ("\n",$match); 

     } # end of if statement 

    } # end of foreach 
} # end of subroutine extractMail 


    for (my $a = 1;$a<=1;$a++){ 

    &extractMail; 

    print @main::match_to_array; 

    } 

回答

2

你误会后。重点是在正确的地方宣布变量。在这种情况下,您应该从子例程中获取值return。此外,通过分配给一个数组

@match_to_array = split /\n/, $match; 

您正在覆盖数组的前一个内容。改为使用push

未经测试:

#!/usr/bin/perl –w 

use strict; 
use warnings; 
use Cwd; 

sub extractMail { 
    my $perl_path = cwd; 
    if (-e 'test.html') { 
     open my $OPENFILE, "$perl_path/test.html" or die "Unable to open file: $!"; 
    } 

    my @match_to_array; 
    while (my $email = <$OPENFILE>) { 
     if ($email =~ /regex to match data/) { 
      my $match = "$1\n"; 
      push @match_to_array, split /\n/, $match; 
     } 
    } 
    return @match_to_array; 
} 


for my $i (1 .. 1) { 
    my @match_to_array = extractMail(); 
    print "@match_to_array\n"; 
} 
+0

感谢您的答复。 “全局符号”有一个错误$ OPENFILE“需要显式包名”。我试着换成'我们的$ OPENFILE',然后使用'$ main :: OPENFILE',它不起作用。 – iridescent 2013-05-07 08:35:30

+1

除了'@ ISA'或应模块的要求(例如'我们的@ EXPORT_OK')之外,不应该使用'our'',并且根本没有理由使用或'$ main ::'。停止使用它们。忘掉它们。你走错了方向。 – ikegami 2013-05-07 10:20:28

+0

注意到@ikegami。 – iridescent 2013-05-07 13:45:46

0
my @email = <OPENFILE>; 
close OPENFILE; 

这可能是问题,那些@email是方含一个元素,即 “[email protected] [email protected] ......” 行之后。

之后你这样做:

foreach my $email (@email) 

这将循环一次,

$email = "[email protected] [email protected] ..." 

那么你的正则表达式删除一切,但“[email protected]”,并导致你的结论您的列表中只有一个元素被处理。

尝试split阅读了生成一个数组你的空间分隔的列表的