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

This might appear very trivial but I have already spent quite some time trying to figure it out and I havent yet!

say, I have a string variable:

$email = "dummy@dumdum.com";
I need to find "@" and replace it with "\@".

So, I really want:

$email = "dummy\@dumdum.com";
How do I do that?!

TIA Monks!

Replies are listed 'Best First'.
Re: How do I find "@" in a string variable?
by davido (Cardinal) on Dec 06, 2006 at 07:11 UTC

    You should first start by using the right kind of quotes. @ is going to interpolate within double quotes, as the sigil of an array. You need single quotes that don't trigger interpolation. Then, you could use the substitution operator like this:

    my $email = 'dummy@dumdum.com'; $email =~ s/\@/\\@/; print $email, "\n";

    ...could... but there's another way too. quotemeta will "escape" any nonword character. While this does include @, it also includes . (dot). That may or may not be a problem for you. You'll have to decide.

    Further reading: Interpolation within quotes is discussed in excellent detail in perlop. The substitution operator is also discussed in perlop, as well as perlre and perlretut.


    Dave

      beautiful! thanks a lot.
Re: How do I find "@" in a string variable?
by chromatic (Archbishop) on Dec 06, 2006 at 07:10 UTC
    say, I have a string variable:

    Unfortunately you don't, because Perl will try to interpolate an array named @dumdum in that double-quoted string. If you have a single-quoted string, or if you have read that string from elsewhere, then this point is moot.

    To escape the @, use a regular expression such as:

    $email =~ s/@/\@/g;

    However, I'm not sure what you're doing in that this is a problem; can you give us more detail on the full problem you want to solve? I suspect that there's probably a much easier solution here.

Re: How do I find "@" in a string variable?
by holli (Abbot) on Dec 06, 2006 at 07:31 UTC
    What? Nobody mentions use strict and use warnings? I mean chances are high there is no @dumdum anywhere in the OP's code, thus strict would have caught that error easily.


    holli, /regexed monk/
Re: How do I find "@" in a string variable?
by madbombX (Hermit) on Dec 06, 2006 at 17:32 UTC
    If you are fishing for email addresses within a string, then take a look at Email::Find and Email::Valid. As holli pointed out, a use strict; use warnings; statement would have caught that. However, this is a another method of fishing for emails.
    use strict; use warnings; use Email::Find; my @emails; my $string = "dummy\@dumdum.com"; my $finder = Email::Find->new(sub { my ($email, $orig_email) = @_; my $escaped = $email->format; $escaped =~ s/@/\\\@/; push @emails, $escaped; return $orig_email; }); $finder->find(\$string); print @emails; __OUTPUT__ dummy\@dumdum.com