How to Properly Validate Email Addresses With Perl

Message in a bottle on the beach that says 'email'

35007 / Getty Images

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.

Whatever the reasons for its invalidity, you do want to catch the broken address — to prompt the user to re-enter 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:

  • Build email validation into the HTML code if you have users type email addresses into a web form.
  • Use Email::Valid->address('') from the Email::Valid CPAN Perl module; see below for details, installation and examples.

Email::Valid Email Address Validation Examples

You can 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.

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.
    • When asked "Would you like me to configure as much as possible automatically?", choose yes.
    • If asked "Is it OK to try to connect to the Internet?", enter yes as well.