Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the @ symbol escaped in this Perl regular expression?

I'm currently covering Perls RegExps and on the whole understand it I think. Escaping characters I have also grasped I think, ie testing for a backslash, denoteable by m/\/ in that the backslash needs to be proceeded buy the \ character first to tell perl in this instance to search for it as apposed to it's usual meaning.

What I don't understand with the code below I have is, this pattern match and why (\) is used when testing the email address with @ symbold (in the if statement expression). I'm not aware @ is a special character needing escaping or have I missed something?.

#!/usr/bin/perl

EMAIL:
{
print("Please enter your email address: ");
$email = <STDIN>;
  if ($email !~ /\@/)
  {
    print("Invalid email address.\n");
    redo EMAIL;
  }
  else
  {
    print("That could be a valid email address.");
  }
}
like image 868
Mike Thornley Avatar asked Feb 08 '11 19:02

Mike Thornley


3 Answers

@ is not a reserved character with respect to regexes, but it is for perl (it's the array symbol)

like image 62
Matt King Avatar answered Nov 15 '22 18:11

Matt King


It's probably escaped to avoid being interpreted as an array sigil. It's not strictly necessary but it's a tough habit to break.

Examples:

$e = "\@foo";
if ($e =~ /@/) {
  print "yay\n";
}

yields:

yay

Same with:

$e = "foo";
if ($e =~ m@foo@) {
  print "yay\n";
}
like image 24
Matt K Avatar answered Nov 15 '22 16:11

Matt K


In Perl, you can escape any potential regex metacharacter and be guaranteed it's a literal.

Also, for @, it's the array sigil, so if there's any chance of it being mistaken for an @/ variable, it's worth escaping.

like image 26
Platinum Azure Avatar answered Nov 15 '22 18:11

Platinum Azure