Home
TeamSite
Doubt in perl
chakri
hi,
Can any one give me the exact diff where single quotes and double quotes work in perl?
At which scenario does single quotes work?
thanks in advance.
regards,
chakri
Find more posts tagged with
Comments
Nidhi_Agrawal
Simple to explain u using one ex.
$var="Nidhi";
print '$var';
print "$var";
output of first print stmt is ...
$var
output of second print stmt is ...
Nidhi
means single quoted dosen't reflect encoded meaning.
Nidhi..
Adam Stoller
Single quotes (and
q{...}
) are used for strings which
do not
need to be /
should not
be "interpolated" (special characters like
$, %, @, \n, \t
, etc. are
not
interpreted) and/or for strings in which it doesn't matter.
Double quotes (and
qq{...}
) are used for strings which
do
need to be /
should
be "interpolated" and/or for strings in which it doesn't matter (
performance-wise / efficiency-wise - if a string does not need to be interpolated you're better off using
single
quotes
).
Occasionally the use of single-quotes where double-quotes would seem logical, is intended - so as to output the actual raw code instead of the interpolated code - but in such situations you should provide clear comments within the code to indicate the intent and rationale.
[best practice: when working with empty strings and strings composed entirely of spaces - always use the
q{...}
form as it is easier to understand that than distinguish between two single-quotes (
''
) and one double-quote (
"
) - and also use
qx{...}
rather than the back-tick (
`...`
)]
Examples:
my $var = 'hello world';
# nothing to be interpolated
print "$var\n";
# variable and newline (\n) interpolated - good
print $var . "\n";
# variable and newline interpolated - good
print '$var\n';
# neither variable nor newline interpolated - bad
print '$var' . '\n';
# neither variable nor newline interpolated - bad
print $var . '\n';
#
variable interpolated - good;
newline not interpolated - bad
print "$var" . '\n';
#
variable interpolated - good;
newline not interpolated - bad
my $var2 = 'hello world\n';
# newline not interpolated - bad
print $var;
#
variable interpolated - good;
newline not interpolated - bad
print "$var";
#
variable interpolated - good;
newline not interpolated - bad
my $var3 = "hello world\n";
# newline interpolated - good (though kind of odd)
print $var;
# variable and newline interpolated - good (though kind of odd)
print "$var";
# variable and newline interpolated - good (though kind of odd)
my $empty = '';
# not clear in all fonts - bad
my $empty = "";
# relatively clear in all fonts, but not efficient - bad
my $empty = q{};
# clear, regardless of font, and efficient - good
my $results = `$cmd`;
# not clear in all fonts - bad
my $results = qx{$cmd};
# clear, regardless of font - good
--fish
Senior Consultant, Quotient Inc.
http://www.quotient-inc.com