Toogit Social Post

Shital Sharma

10 months ago
Hello,

I need help in Perl pattern matching issue.

I've an email field of a certain array (say $Arr[0]) that usually contains only a mail of a correct ad desired form, say:
$Arr[0] = shital@yah.com

sometimes this desired mail is mixed with other ones, and sometimes is absent, eg:

$Arr[0] = shital@yah.com --- xyz@yah1.com ---- abc@yah2.com
$Arr[0] = shital@NOTyah.com

(please note that "---" is NOT a standard separator, it can varies).

I must check this situation and maintain only the desired addresses.
So I've written the following conditional statement:

if ( $Campi[0] =~ /\@yah.com/) {
$Campi[0] =~ m/^([-a-z0-9]+)\yah.com$/; #keep only the @yah.com address
} else {
$Campi[0] = "lacks mail @yah.com"; #print a standard msg about the absence of @yah.com
}

The line
$Campi[0] =~ m/^([-a-z0-9]+)\yah.com$/; #keep only the @yah.com address
does not return the desired result: please can you help me?
7 Likes
5 comments, 3 Followers

Try below:

# changed \b to explicit tags to get actual boundary, added period to valid characters, and /i to do case-insensitive
# also escaped periods in domain
if ( $Campi[0] =~ /(?:^|\s)([-a-z0-9.]+\@yah\.com)(?:$|\s)/i) {
$Campi[0] = $1;
} else {
$Campi[0] = 'lacks mail @yah.com'; #print a standard msg about the absence of @yah.com
}

by Pratik Bhor 10 months ago

use Email::Address;
# will not work if there are emails of the form "Name" <email@yah.com> (needs some extras if this is the case)
my @email = grep /\@yah\.com$/i, Email::Address->parse($Campi[0]);
if ( @email ) {
$Campi[0] = $email[0]; # arbitrarily pick the first one if there are multiple
} else {
# changed to single-quotes to avoid interpolation (which use strict and use warnings would have told you about)
$Campi[0] = 'lacks mail @yah.com'; #print a standard msg about the absence of @yah.com
}

P.S. I haven't tested above code.. Pardon me for syntax errors

by Swapnil 10 months ago

Thanks @Swapnil. Could you please suggest me related CPAN module? I tried searching but getting confused which one to use

by Shital Sharma 10 months ago

I think you should use CPAN module to do the actual parsing.
It looks like you are not doing "use strict" and "use warnings" . You should always do this.

by Swapnil 10 months ago