Perl string quotation operators (q, qq, qr and qx)

In scripting programming languages such as perl, php and python use string quotation extensively. To include single or double quote inside the string quotation, you'll have escape the character with a backslash. Perl string quotation operators (q, qq and qx) let you avoid putting too many backslashes into quoted strings.

q/STRING/, or q(STRING) - Single Quotes, does not allow interpolation.
qq/STRING/, or qq(STRING) - Double Quotes, allow interpolation.
qr/EXPR/, or qr(EXPR) - Regexp-like quote
qx/STRING/, or qx(STRING) - Backquote, executes external command inside backquotes.

The difference between the single quote and double quote is interpolation. Double quote allows string to be replaced with the value of that variable inside the quote, while single quote doesn't allow it.

The q operator (single quote) example:

#!/usr/bin/perl -w
$name = "Cindy";
$str = q/This is $name's dog./;
print $str;

The above script prints the following output.

This is $name's dog.

The qq operator (double quote) example:

#!/usr/bin/perl -w
$name = "Cindy";
$str = qq(This is $name's dog.);
print $str;

The above script prints the following output.

This is Cindy's dog.

The qr operator (regex quote) example:

#!/usr/bin/perl -w
$regex = qr/[io]n/i;
print $regex, "\n";
$string = "I am on chair in the room.";
$string =~ s/$regex/XX/mg;
print $string, "\n";

The above script prints the following output.

I am XX chair XX the room.

Regular Expression Options:

m   Treat string as multiple lines.
s   Treat string as single line. (Make . match a newline)
i   Do case-insensitive pattern matching.
x   Use extended regular expressions.
p   When matching preserve a copy of the matched string so
     that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined.
o   Compile pattern only once.

The qx operator (backquote) example:

#!/usr/bin/perl -w
$str = qx(date);
print $str;

The above script prints the following output.

Wed May 18 19:30:36 CDT 2011

If the delimiter is an opening bracket or parenthesis, the final delimiter will be the corresponding closing bracket or parenthesis.

Tags: 

Comments

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.