Sawsuh
Sawsuh

Reputation: 13

perl read line by line with global variable

i have a perl script-

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

the file emails is:

sdfasd@asd 
asdf

so, as you can see, the script will not match regex to any of the lines. however, it outputs this-

no emails
no emails

i want it to output 'no emails' ONCE if it doesn't match the regex pattern at all. If it only matches the regex pattern just once, it will print that line and output 'no emails' for the other line :( I just want it to output either JUST the lines with the emails, or output 1 line that says 'no emails'. Thanks in advance.

Upvotes: 1

Views: 125

Answers (2)

Kenosis
Kenosis

Reputation: 6204

Consider using a module, such as Regexp::Common::Email::Address, "...to match email addresses as defined by 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;

Hope this helps!

Upvotes: 3

user4035
user4035

Reputation: 23729

Try this, I changed the emails file name in order to test on my machine:

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

Test file

sdfasd@asd
asdf
[email protected]
[email protected]

Output

[email protected]
[email protected]

Upvotes: 2

Related Questions