Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- Using strings as keys of hash
November 29, 2008, 11:09 pm
rate this thread
It seems that if strings are keys, the single quote can be omitted. I
don't see why on perl hash tutorial webpage such as
Can somebody give me a brief explanation why the single quote can be
omitted if the strings are used as the keys of a hash?
my %hash = (
Fred => 'Flintstone',
Barney => 'Rubble'
# I can use the following code as well.
#my %hash = (
# 'Fred' => 'Flintstone',
# 'Barney' => 'Rubble'
#The strings does not have single quotes as well.
- Martien Verbruggen
November 29, 2008, 11:26 pm
Re: Using strings as keys of hash
It really has nothing to do with strings being keys in a hash, and
everything to do with the => operator. The reason is simply that that
is how the => operator was designed.
$ perldoc perlop
The "=>" operator is a synonym for the comma, but forces any word
(consisting entirely of word characters) to its left to be
interpreted as a string (as of 5.001). This includes words that
might otherwise be considered a constant or function call.
Note that the => is simply a comma, except for the auto-quoting
behaviour of its left operand. It can be used in other places where a
comma would normally be used, such as subroutine calls.
my $foo = Foo->new(arg1 => 12, arg3 => 4);
is exactly equivalent to
my $foo = Foo->new("arg1", 12, "arg3", 4);
(or with single quotes if you prefer). There is no hash involved at any
Martien Verbruggen | The gene pool could use a little
email@example.com | chlorine.
- » How to forbid functions of some package be introduced to the global name space?
- — Next thread in » PERL Discussions