Search code examples
regexperlsubdomaintld

Perl extract domain name from email address inc tld but excluding subdomains


I'm trying to do what the title says and I've got this:

sub getDomain {

    my $scalarRef = shift;
    my @from_domain = split(/\@/,$$scalarRef);

    if($from_domain[1] =~ m/^.*?(\w+\.\w+)$/){
       print "$from_domain[1] $1" if($username eq 'xxx');
       return $1;
    }
}

Works fine for [email protected] returning domain.com, but of course domain.co.uk will return .co.uk and I need domain.co.uk. Any suggestions on how to proceed with this one, I'm guessing a module and some suggest some kind of tld lookup table.


Solution

  • Don't use a RegExp.

    use Email::Address;
    my ($addr) = Email::Address->parse('[email protected]');
    print "Domain: ".$addr->host."\n";
    print "User:   ".$addr->user."\n";
    

    Prints:

    Domain: domain.co.uk
    User:   foo