【问题标题】:perl read line by line with global variableperl 使用全局变量逐行读取
【发布时间】:2014-01-31 04:59:04
【问题描述】:

我有一个 perl 脚本-

#!/usr/bin/perl;
my $email = '[a-zA-Z0-9._]+@[a-zA-Z0-9._]+.[a-zA-Z0-9._]{2,4}';
open(FILE,'emails');
while (<FILE>) { 
    my $emails_not_found = 1;
    if ( m/$email/ ) { 
        print($_); 
        my $emails_not_found = 0; 
    } 
    if ( $emails_not_found ) {
        print "no emails\n";
    }
}  
close FILE;

文件emails是:

sdfasd@asd 
asdf

所以,如您所见,脚本不会将正则表达式与任何行匹配。但是,它会输出这个-

no emails
no emails

如果它根本不匹配正则表达式模式,我希望它一次输出“无电子邮件”。如果它只匹配正则表达式模式一次,它将打印该行并为另一行输出“无电子邮件” line :( 我只是希望它只输出带有电子邮件的行,或者输出 1 行显示“没有电子邮件”。提前致谢。

【问题讨论】:

  • 为什么要使用不检查有效电子邮件地址的正则表达式检查电子邮件地址? :-)

标签: regex perl email


【解决方案1】:

考虑使用一个模块,例如Regexp::Common::Email::Address,“...以匹配 RFC 2822 定义的电子邮件地址”:

use strict;
use warnings;
use Regexp::Common qw/Email::Address/;

my $emailFound = 0;
open my $fh, '<', 'emails' or die $!;

while (<$fh>) {
    if (/$RE{Email}{Address}/) {
        print;
        $emailFound = 1;
    }
}

close $fh;

print "no emails\n" if !$emailFound;

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    试试这个,我更改了电子邮件文件名以便在我的机器上测试:

    #!/usr/bin/perl
    
    #output either JUST the lines with emails
    # or
    #1 line that says 'no emails'
    use strict;
    use warnings;
    
    my $email = '[a-z0-9\._]+@[a-z0-9\._]+\.[a-z0-9\._]{2,4}';
    open(FILE,'./email.txt');
    my $emails_not_found = 1;
    while (<FILE>) {
        if ( m/$email/i ) {
            print($_);
            $emails_not_found = 0;
        }
    }
    
    if ( $emails_not_found == 1) {
        print "no emails\n";
    }
    close FILE;
    

    测试文件

    sdfasd@asd
    asdf
    aaa@aaa.com
    AAA@AAA.COM
    

    输出

    aaa@aaa.com
    AAA@AAA.COM
    

    【讨论】:

    • 非常感谢 :) 我感谢您的详细说明-它使这更容易理解。你知道,你不需要做 $emails_not_found == 1,因为如果值是 1 或 0,perl 可以将它读取为布尔值,所以你可以把它写成 if ( $emails_not_found )
    猜你喜欢
    • 2021-04-24
    • 2014-04-28
    • 1970-01-01
    • 2018-04-25
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多