What is the difference between '' and ""

07/03/2013 - 17:32 von Ying Gan | Report spam

when should I write: $input="";

when should I write: $input='';

And what exactly is the difference?

Thank you very much!

Lesen sie die antworten

#1 Christian Winter
07/03/2013 - 19:07 | Warnen spam
Am 07.03.2013 17:32, schrieb Ying Gan:
when should I write: $input="";

when should I write: $input='';

And what exactly is the difference?

The difference is that double quotes interpolate while single quotes
don't. Interpolate means that they try to resolve variables starting
with $ or @ to their values (i.e. array elements, arrays, array
slices, hash element or array-/hash subscripts) as well as process
all kinds of escape sequences (starting with a backslash).

The difference will become visible with a small script like this:

use strict;
use warnings;

my $inside = 'downstairs';

my $double = "I am $inside";
print $double;

my $single = 'I am $inside';
print $single;

While inside the double quotes $inside gets interpolated to its value
and $double thus contains the string "I am downstairs" and a newline,
$single still contains the literal characters that were assigned inside
the single quotes.

Type "perldoc perlop" and scroll down to the section named "Quotes and
Quote-like Operators" to get an in-depth description about Perl's
quoting features.

If you feel befuddled by Perl's strange names like scalars, subscripts,
slices etc. have a look at "perldoc perldata", where Perl's variable
types are explained.

It's hard to give a general rule when to use which quotes, but my rule
of thumb is to use single quotes as much as possible, because double
quotes are much more error prone. One means to output a text with an
email address, for example, but perl sees the name of an array and
replaces it with nothing:

print "Send a mail to to reply";
might only output
Send a mail nobody to reply

Mistakes like this are also a reason why one should always put
use strict;
use warnings;
at the top of scripts (it might become necessary later to disable
the one or other kind of warning, but cross that bridge when you
get to it). Without them, perl would silently replace the @invalid
in the example with an empty string, while with warnings it will
tell you something along the lines of
Possible unintended interpolation of @invalid in string at - line 5
Name "main::invalid" used only once: possible typo at - line 1.

It might be tempting to use double quotes and write something like
print "Result: $obj->{name} lives at $obj->{city}";
but you'll sooner or later make a mistake that will be that much
harder to trace than if you wrote
print "Result: " .$obj->{"name"}. " lives at " .$obj->{"city"}. "";
or even
printf "Result: %s lives at %s", $obj->{"name"}, $obj->{"city"};


Ähnliche fragen