Why is the @ character escaped in this Perl regex?

I am currently reviewing Perls RegExps and generally understand what I think. Escaping characters that I also understood, such as testing for a backslash, denoted by m / \ /, is that the backslash should continue, buy the \ character first to tell perl in this case, to find it like it has been attributed to the usual meaning.

What I don’t understand with the code below is the match of this pattern and why (\) is used when testing the email address with @symbold (in the if statement). I don’t know that @ is a special character who needs to slip away or am I missing 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."); } } 
+8
regex perl escaping
source share
4 answers

This was probably avoided so as not to be interpreted as an array signal. This is not strictly necessary, but it is a tough habit to break.

Examples:

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

gives:

 yay 

Same:

 $e = "foo"; if ($e =~ m@foo@) { print "yay\n"; } 
+11
source share

@ is not a reserved character in relation to regular expressions, but it is intended for perl (it is an array character)

+8
source share

In Perl, you can avoid any potential regular expression metacharacter and be guaranteed to be its literal.

In addition, for @ it is a sigil array, so if it is likely that it is mistaken for the @/ variable, it is worth slipping away.

+5
source share

Arrays are interpolated both in double-quoted strings and in regular expressions in Perl with a special variable $" (by default a whitespace character) passing between each element:

 my @array = ('a', 'b', 'c'); print "@array"; # prints "abc" print "abc" =~ /@array/; # prints "1" 

I rarely use this function, but sometimes it comes in handy, for example:

 sub line_matches_words { my ($line, @words) = @_; local $" = '[ \t]+'; return $line =~ /^[ \t]*@words[ \t]*$/; } 
+5
source share

All Articles