Search⌘ K

Solution Review: Extract Email Addresses

Explore how to extract email addresses using Perl by reviewing a solution that combines file reading, regular expressions, and looping techniques. Learn how each regex component works together to capture and print email matches efficiently from a given text file.

We'll cover the following...

Solution

Let’s look at the solution before jumping into the explanation:

Perl
# Assume that $file is already defined and it contains the name of the file
open my $fh, '<', $file;
my $username = qr/\w+/;
my $domain = qr/\w+/;
my $top_level = qr/\w{2,3}/;
my $country = qr/[a-z]{2,3}/;
my $email = qr/$username\@$domain\.$top_level(\.$country)?/;
while(<$fh>) {
say "$1" while $_ =~ /($email)/ig;
}

Note: You can try out ...