Perl

  1. Home
  2. Computing & Technology
  3. Perl

Beginning Perl Tutorial - Data Types: Scalars

Single and Double Quoted Strings

From About.com

Next: Playing with Scalars

A string is a sequence of characters - a bit like a sentence. Strings can be contained within single or double quotes depending on what you're trying to accomplish. When a string is held by single quotes, there are only two special characters to remember: the backslash (\) and the single quote itself ('). For obvious reasons, it would be impossible to use a single quote within a string since it is, in fact, the character that designates the start and end of the string. In order to do so, you must escape the quote using a backslash character, like so:

$aString = 'It\'s necessary to escape the single quote.';
But then what if you want a backslash at the end of your string? It must be escaped, using itself:
$aString = 'You must escape the \, but only if it\'s at the end:\\';
So what's the \n character for a newline in the earlier example? Double quotes around your string allows the use of certain special control characters that all begin with the escaping backslash. Characters like \n for a newline or \t for a tab. It also allows your variables (remember $my_name?) to be interpolated, which essentially means replaced with their value in the final output. Of course, with double quotes, the backslash and double quote characters must also be escaped:
$aString = "It's fine to leave a single quote free.\n A \" and a \\ must be escaped.\n";
So lets modify our two line program above just to see what the output looks like when we use the different quotes:
#!/usr/local/bin/perl
$my_name = 'Bobby';
print "$my_name\n";
print '$my_name\n';
You should see some output like so:
$ ./simpleProgram.pl
Bobby
$my_name\n$
See how both the $my_name variable and the \n newline are printed literally in the second, single quoted string?

Next: Playing with Scalars

Explore Perl

About.com Special Features

Perl

  1. Home
  2. Computing & Technology
  3. Perl
  4. Perl Tutorials
  5. Beginning Perl Tutorial - Data Types: Scalars

©2009 About.com, a part of The New York Times Company.

All rights reserved.