Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Hash Syntax Question

by mjscott2702 (Pilgrim)
on Jul 25, 2007 at 21:00 UTC ( #628791=note: print w/replies, xml ) Need Help??

in reply to Hash Syntax Question

In this context, is there any difference between using single or double quotes, apart from the fact that single quotes will prevent variable interpolation?
Maybe I've been using Java too much lately, but now I am getting paranoid about the number of "objects" I create ...

Replies are listed 'Best First'.
Re^2: Hash Syntax Question
by Joost (Canon) on Jul 25, 2007 at 21:24 UTC
    No difference except for the one you mentioned. single and double-quoted strings both result in the same object except for the variable interpolation and related character escape rules.

    In theory, if you don't need interpolation, using single quotes could compile a tiny bit faster, but a) perl compiles blazingly fast compared to most languages, and b) the time needed to analyze a quoted string is probably dwarfed by the time needed to load the perl interpreter and the rest of the code. Don't worry about it.

    Also, using double-quotes makes it slightly easier to insert variables into the string later, which is why i generally prefer to use double-quoted strings for all literals that don't contain a lot of "meta" characters.

      And, if there's nothing in the string to interpolate, perl changes the double quotes to single quotes:

      zippy:~/scripts$ deparse -e '$h{q[one]} = 1; $h{qq[two]} = 2; $x = q[t +hr]; $h{qq[${x}ee]} = 3;' $h{'one'} = 1; $h{'two'} = 2; $x = 'thr'; $h{"${x}ee"} = 3; -e syntax OK

        Well, deparse isn't 100% reliable, and secondly, it still takes some analyzing to determine that there are no strings to be interpolated in the double-quoted string.

        Probably not much more than analyzing a single-quoted string for \' escapes though, since you'd only have to test for the sigils.

        update: what I mean to say is, all this stuff is done at compile-time - i.e. normally, it's done only once per string; when the code is loaded. It has no impact at all after that. Run-time perl has no distinction between single and double quoted strings - it all compiles to a fixed string (for constant strings) or a number of concatenation operations on variables and constant strings (for interpolations).

Re^2: Hash Syntax Question
by dsheroh (Monsignor) on Jul 25, 2007 at 21:22 UTC
    Nope. As a rule, interpolation is the only difference between single and double quotes in Perl.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://628791]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (2)
As of 2023-03-24 22:34 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (62 votes). Check out past polls.