Main Content

Single and double quotes strings in Perl - what is the difference?

Archive - Originally posted on "The Horse's Mouth" - 2011-08-30 05:56:44 - Graham Ellis

In Perl, there's usually more than one way of doing it ...

If you're writing a string of text into your program, your first possibility is to use single quotes - in which case you're writing a literal string with everything between the single quote chartacters included exactly in the string. And your second possibility is to use double quotes - which are actually an operator, and \ $ and @ characters within the string trigger "escaping" of the following characters, and inclusion of variable contents.

Here's some code to show that:

  $name = Bob;
  @choice = ("Tea",'Coffee');
 
  print 'Here is $name choosing from @choice\n';
  print "\n";
  print "Here is $name choosing from @choice\n";


And that runs as follows:

  munchkin:ap3 grahamellis$ perl asy
  Here is $name choosing from @choice\n
  Here is Bob choosing from Tea Coffee
  munchkin:ap3 grahamellis$


If you really want to include a " within a "'d string, you can use \", but you shouldn't be able to use the same technique to include a ' within a 'd string (in practise, there's an exception made that lets you do so!!). However, all this extra quoting of delimiters gets messy so you can choose your own special characters as the delimiter using the qq notation for a double quoted string and the q notation for a single quoted string:

  $name = Bob;
  @choice = (qq!Tea!,q%Coffee%);
 
  print q#Here is $name choosing from @choice\n#;
  print qq"\n";
  print qq(Here is $name choosing from @choice\n);


Output is identical to what you saw just above. Just about any special character may be used - even the # which is normally used for comments; if you use an open bracket or brace, then the closing character should be the opposing bracket of brace - otherwise the close is the same as the open. And your choice of special character only lasts for the one string.

Want still more flexibilty? You can use a "here document" where the delimiter used is an entire word of your choice! There's a previous article about here documents ... [here] ;-).