http://www.perlmonks.org?node_id=863171

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

Hello Perl Monks, Trying to parse an e-mail address vis:

$adr = "User@domain.com"; @ads = split(/@/,$adr);

What I was expecting was to achieve was: @ads[0]="User" @ads1="domain.com" what I get however is: @ads[0]="User.com" @ads1="" Aware that @ is a special character I tried various combinations of "\" and "@" as the split argument but alas the result is the same. As a slightly different approach I tried:

$sub = $adr; $sub =~ s/@/\@/;

but again this gave $sub = "User.com" I guess I need to change the syntax somehow to accept the "@" or try a different approach altogether. Any suggestions gratefully received.

Thanks to everyone who responded for all the help.

Replies are listed 'Best First'.
Re: Parsing an email address
by Corion (Patriarch) on Oct 03, 2010 at 12:34 UTC

    strict would have prevented you from making the error of writing "User@domain.com". What Perl sees is the array @domain, which is empty and thus interpolates into an empty string. You want to use single quotes:

    my $adr = 'User@domain.com'; ...
      ...or, alternatively, put a backslash in front of '@':

      my $adr= "User\@domain.com";

      Another thing that might help with this is using an editor with good syntax highlighting for perl -- one which will show special characters like @ when they are used inside double quotes, etc.

      Using an editor which does not have any syntax highlighting for the language you are coding in seems just plain silly.

Re: Parsing an email address
by AnomalousMonk (Archbishop) on Oct 03, 2010 at 12:54 UTC
Re: Parsing an email address
by TomDLux (Vicar) on Oct 03, 2010 at 18:29 UTC

    The real, classic mistake is looking at the outputs and finding them wrong, but not looking at the input, not testing it in the debugger or playing with it in an interactive session.

    You weren't getting the results you wanted in @ads, but never verified what you started with in $ads. If the data is wrong, a correct split will not produce the expected results.

    You might have used the debugger to interact with your program: perl -d ads.pl. You can also start up the debugger without a program, to experiment with commands: perl -demo. ( Actually it should be perl -de 0, but what you give after the -e doesn't matter, and demo is rememberable.)

    As Occam said: Entia non sunt multiplicanda praeter necessitatem.