Re: Hash Syntax Question
by FunkyMonk (Chancellor) on Jul 25, 2007 at 20:11 UTC
|
| [reply] [d/l] [select] |
|
also be aware of the following little gotcha:
perl -wMstrict -e "my %h; $h{shift} = 'foo'; print %h" bar
shiftfoo
perl -wMstrict -e "my %h; $h{shift()} = 'foo'; print %h" bar
barfoo
| [reply] [d/l] |
|
ok thanks that was very helpful :-)
| [reply] |
Re: Hash Syntax Question
by philcrow (Priest) on Jul 25, 2007 at 20:08 UTC
|
The first one is fine, unless there are funny characters (like spaces or other punctuation) in the key name.
Phil
| [reply] |
Re: Hash Syntax Question
by Fletch (Bishop) on Jul 25, 2007 at 20:15 UTC
|
The first contravenes PBP 45 ("Don't use barewords."), but behavior-wise as long as it's a plain bareword there should be no difference.
Stylistically though it'll get you disapproving glares from the purists (granted I still violate 45 myself out of old habits; working with Ruby is slowly changing that (although too much Rails makes me tend to try $hash{ :key } instead . . . )).
| [reply] [d/l] |
Re: Hash Syntax Question
by mjscott2702 (Pilgrim) on Jul 25, 2007 at 21:00 UTC
|
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 ... | [reply] |
|
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.
| [reply] |
|
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
| [reply] [d/l] [select] |
|
|
Nope. As a rule, interpolation is the only difference between single and double quotes in Perl.
| [reply] |