使用main ::打印显示其所有元素的数组变量。

时间:2013-05-07 04:27:18

标签: arrays perl variables

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

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

输入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;

    }

2 个答案:

答案 0 :(得分: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";
}

答案 1 :(得分: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以从空格分隔列表中生成数组