1. Computing

Discuss in my forum

How to Validate Email Addresses with Perl

By , About.com Guide

Is it valid, and will it work? If you collect or use email addresses anywhere in your Perl scripts and programs, you possibly collect many addresses that do not work. One may lack a letter in the domain name, another may have a disallowed character too much.

Whatever the reasons for its invalidity, you do want to catch the broken address — to prompt the user to re-inter maybe, or to avoid sending an email that's sure to go nowhere.

In Perl, you can concoct a complicated regular expression, of course; or you turn to a handy module that already has one built in and can check domain names, too.

Validate Email Addresses with Perl

To check email addresses for the well-formedness and validity in a Perl script or program:

Email::Valid Email Address Validation Examples

Assuming $email_address holds the address to be checked, you can check its validity using:

#!/usr/bin/perl
use Email::Valid

$email_address = 'me@@example.com';
if (Email::Valid->address($email_address)) {
    # The email address is valid
} else {
    # The email address is not valid
}

You can also have Email::Valid check for valid top-level domains (making sure ".com", ".net", ".cn" or another valid domain name is at the email address's very end). Make sure the Net::Domain::TLD module is installed.

#!/usr/bin/perl
use Email::Valid

$email_address = 'me@@example.com';
if (Email::Valid->address(-address  => $email_address,
                          -tldcheck => 1)) {
    # The email address is valid
} else {
    # The email address is not valid
}

Install the Email::Valid Perl Module

To equip your Perl installation with the Email::Valid module for validating email address correctness:

  • Open a command prompt.
    • Under Mac and Linux, open the Terminal application, for example.
  • Type sudo perl -MCPAN -e 'install Email::Valid' (Mac and Linux) or perl -MCPAN -e 'install Email::Valid'.
  • Press Enter.
    • Enter the super user password and press Enter if prompted.
    • Asked Would you like me to configure as much as possible automatically?, choose "yes" unless you know
    • Asked Is it OK to try to connect to the Internet?, enter "yes" as well.

©2013 About.com. All rights reserved.