bizactuator has asked for the wisdom of the Perl Monks concerning the following question:

I have a form that people fill out and I've seen people putting their email like this:

My name <email@example.com>

So using Perl, what is the best way to get their Name in a variable and the email in another, IF they put it like that, and if they put it like this:

My Name email@example.com

I tried checking if < existed:

$_email = param("email"); if($_email =~ /\>/) { # split value }


but it did not work right.

anyone have any code already that does it? or is there a module that already extrapolates the name and email from a field?
Thank you so much in advance.
my best,
-Rich

Replies are listed 'Best First'.
Re: Getting email from fields
by haukex (Archbishop) on Oct 27, 2017 at 06:50 UTC

    Email addresses can actually get pretty complex. I recommend you use a module like Email::Address:

    use Email::Address; print $_->address,"\n" for Email::Address->parse( 'My Name email@example1.com '. 'My name <email@example2.com>'); __END__ email@example1.com email@example2.com
Re: Getting email from fields
by Your Mother (Archbishop) on Oct 27, 2017 at 06:58 UTC

    Mail::Address maybe, probably. :P

    use Mail::Address; my $raw = 'My Name <email@example.com>'; my @addresses = Mail::Address->parse($raw); print $_->address, $/ for @addresses;

    Update: posted before I saw haukex's answer. I am not sure which of Mail::Address and Email::Address is a better choice or if they are equivalent. The former was already installed on my box. :P

Re: Getting email from fields
by kcott (Archbishop) on Oct 27, 2017 at 06:10 UTC

    G'day bizactuator,

    You can capture the two parts with this regex:

    /^(.+?)\s+<?(\S+?)>?$/

    My test:

    $ perl -E 'say join " = ", /^(.+?)\s+<?(\S+?)>?$/ for q{My name <email +@example.com>}, q{My Name email@example.com}' My name = email@example.com My Name = email@example.com

    — Ken

      awesome, so would I do it like this then:

      my ($name,$email) = join " = ", /^(.+?)\s+<?(\S+?)>?$/ for param("emai +l");


      like that?

      That does not look right to me, but I'm a novice. Lol

        No, that would give you one problem and one misconception. The problem is that the join will give you one scalar whereas you are assigning to a list (of two scalars). The misconception is that if you have only one scalar value for param("email") then the for is irrelevant since it is there to loop over all values and you have only one. kcott has included the for in his example because he is showing you the results of both input forms.

        If you want the name and email as separate scalars then just do this:

        #!/usr/bin/env perl use strict; use warnings; use utf8; # ... something here which defines param() my $fullmail = param ("email"); my ($name,$email) = ($fullmail =~ /^(.+?)\s+<?(\S+?)>?$/); print "Name is $name, Email is $email, Original is $fullmail\n";