0

@main::match_to_array仅打印出数组中的最后一个元素,@match_to_array而不是整个数组。

我参考这个 SO 链接做了我的代码。

输入 HTML 包括 dmit@sp.com ems@es.com dew@es.com dmit@sp.com erg@es.com

#!/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;

    }
4

2 回答 2

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";
}
于 2013-05-07T04:41:09.273 回答
0
my @email = <OPENFILE>;
close OPENFILE;

这可能是问题所在,在这些行之后@email 包含一个元素,即“dmit@sp.com ems@es.com ...”。

之后你这样做:

foreach my $email (@email)

这将循环一次,与

$email = "dmit@sp.com ems@es.com ..."

然后,您的正则表达式会删除除“dmit@sp.com”之外的所有内容,并得出结论,即仅处理列表中的一个元素。

尝试阅读split以从您的空格分隔列表中生成一个数组

于 2013-05-07T09:00:36.507 回答