Thursday, January 27, 2011

Transform email address found in txt file into "mailto" link

"test.txt" file contains the following line: My address is username@host.com


SCRIPT FILE
open FILEHANDLE, 'test.txt' or die; # text.txt file is in the same directory with the perl script
$string = '';
while (<FILEHANDLE>)
{
$string .= $_;# $string will contain all the file content in the end
}
$string =~ s{
       \b
       (
         \w+ #first part the username
         \@
         [-a-z0-9]+(\.[-a-z0-9]+) #second part the host name. This could be replaced with \w
       )
       \b
    }{<a href="mailto:$1">$1</a>}gix;

The results is : <a href="mailto:username@host.com">username@host.com</a>

The /x modifier appears at the end and does two things for the regular expression. First, whitespace will be ignored and it allows you to add comments with a leading #.

No comments:

Post a Comment