Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Correct keys in hashes

by Scarborough (Hermit)
on Aug 25, 2004 at 10:53 UTC ( #385641=perlquestion: print w/replies, xml ) Need Help??
Scarborough has asked for the wisdom of the Perl Monks concerning the following question:

Hi Folks

Can anyone tell me or direct me to, an explantion of why

%hash = ('name'=>'Scarborough'); #is better then %hash = (name =>'Scarborough'); #and $hash{'name'}; #is better then $hash{name} #when both ways seem work
Thanks for any help you can offer.

Replies are listed 'Best First'.
Re: Correct keys in hashes
by Joost (Canon) on Aug 25, 2004 at 11:25 UTC
    Those examples are exactly equivalent. In general the only problem with these automatically quoted strings is that they need to be valid identifiers or integral numbers not starting with 0 (more or less matching /^([1-9]\d*)|([a-zA-Z_]\w*)$/).

    update: as demonstrated by ikegami below, actually only valid identifiers are quoted: that means anything matching /^[a-zA-Z_]\w*$/ but not numbers.

    As long as you use valid keys, and don't use version strings (/^v\d+$/) the quoted and unquoted keys are equivalent.

    The version strings implementation makes $hash{v80} != $hash{'v80'} etc. in some versions of perl, so for portability these keys should always be quoted.

    So, in short, if you don't want to think about the keys you use, quote them, but usually an intuitive key name can be used unquoted.

      automatically quoted strings [...] more or less matching /^([1-9]\d*)|([a-zA-Z_]\w*)$/

      No, it doesn't match numbers at all. If => autoquoted numbers, the key would be a bunch of 9s in the example below. Non-strings (numbers, references, etc) are converted to strings (although I think there is planned change to preserve the type of the key, maybe in perl6), but that's not the same as quoting. I think that means that if and only if it's a valid subroutine name, it'll get autoquoted.

      >perl -le " %a = (999999999999999999999999999999999999 => ''); print keys %a"; 1e+036 >perl -le " %a = (999999999999999999999999999999999999, ''); print keys %a"; 1e+036
Re: Correct keys in hashes
by cchampion (Curate) on Aug 25, 2004 at 11:19 UTC
Re: Correct keys in hashes
by davorg (Chancellor) on Aug 25, 2004 at 11:03 UTC

    Why do you say that your first examples are better? I don't see why they are better.

    Of course, with your second examples, it's important to know the quoting rules for a) the "fat comma" and b) hash index braces.


    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Correct keys in hashes
by muntfish (Chaplain) on Aug 25, 2004 at 11:01 UTC

    They are equivalent, aren't they? Where is it said that quoting the key is better?

    (Of course, if your key contains symbols or whitespace or something, then you have to quote it.)

      I've had people correct me on some posts in the past without explanation so I just decided to ask.
      But the piont about white space makes sense.

      Thanks for your help.

Re: Correct keys in hashes
by Aristotle (Chancellor) on Aug 25, 2004 at 16:10 UTC

    I almost always prefer the quote-less versions. You do have to understand the quoting rules to read them, but I still prefer them. Quoting everything explicitly can make code look really busy, particularly when there are a lot of key-value-pairs. It makes for a lot of clutter. Using the fat comma makes things much calmer.

    Also, I use a syntax highlighting editor, which I consider to have been quite beneficial to my coding style in general. In this case, the highlighting reminds me that the bits I'm looking at are actually strings. It also encourages me to disambiguate function calls explicitly, for my own benefit, because the highlighting needs the cues to pick up the difference.

    Makeshifts last the longest.

Re: Correct keys in hashes
by benizi (Hermit) on Aug 25, 2004 at 17:59 UTC

    In older versions of perl, there was at least one good reason to prefer $hash{'name'} to $hash{name}. Observe:

    $ perl -v This is perl, version 5.004_04 built for sun4-solaris $ perl -lwe 'use strict; sub ambiguous { } my %hash; $hash{ambiguous}= +5; print "but not fatal"' Ambiguous use of {ambiguous} resolved to {"ambiguous"} at -e line 1. but not fatal

    So, if you're really worried about backwards compatibility (or, as in my case, you're stuck using an old perl via a CGI server), it might be beneficial to use the quotes. (I can't tell exactly, but it looks like this was fixed in 5.005_something)

    Update: what kwoff said: better example of CGI-related error that not-quoting leads to.

Re: Correct keys in hashes
by saberworks (Curate) on Aug 25, 2004 at 14:39 UTC
    Perhaps you are confusing perl with PHP. In PHP, you should always quote your hash keys, otherwise warnings are generated. Warnings of this type aren't enabled by default on PHP, so a lot of people don't realize that you can't say something like $hash[key] legally. It works, but if you benchmark it, it's something like 50% slower, simply because of all the warnings that are generated and silently discarded. To see these warnings in PHP, use the error_reporting function like: error_reporting(E_ALL);
Re: Correct keys in hashes
by radiantmatrix (Parson) on Aug 25, 2004 at 18:47 UTC
    It isn't really better, per se. In any case, here's the rationale on why some people prefer to quote hash keys:

    The unquoted strings (a.k.a. "bareword strings") are ambiguous. If, for some strange reason, the Perl interpreter decides to interpret name as a function or somesuch, there could be logic bugs. So, some consider it good practice merely to quote all bareword strings (hash keys included) simply to promote readability and "take no risks".

    The fact of the matter is, though, that the likelihood of a bareword being confusing to the interpreter and not generating a warning or error -- even in future Perl releases -- is fantastically small. So, don't worry about it!

    In any case, just pick one and be consistent. If you think quoted strings are better in place of barewords, go ahead and use them -- just use them in every case. Consistency makes for far more readable (and maintainable) code than adherance to anyone else's ideas of "right code".

    $me = rand($hacker{perl});

      If, for some strange reason, the Perl interpreter decides to interpret name as a function or somesuch

      But it doesn't decide "for some strange reason". That sounds as if it was a matter dependent on rolling dice. The decision is actually deterministic and comprehensible.

      Makeshifts last the longest.

        I see you mistook my meaning. I was speaking of Perl the person. :P (Or, rather, Perl as a community).
        $me = rand($hacker{perl});
Re: Correct keys in hashes
by gmpassos (Priest) on Aug 25, 2004 at 17:52 UTC
    Quote a key is NOT better than just use a word! When a HASH keys is declared a word will be a word (will never be treated as a sub call). So, write (time => 'foo') is not the same of (time() => 'foo'). If you want to lose your time quoting this is your choice.

    Graciliano M. P.
    "Creativity is the expression of the liberty".

Re: Correct keys in hashes
by flogic (Acolyte) on Aug 25, 2004 at 19:04 UTC
    I used to always quote them. But that took forever so now I don't. However for the parnoid it's probably better. Lest some day you do something like...
    my($count)=0; sub name() {'autoname'.$count++} $foo{name}='bob';
    I'll still probably skip the quotes until the it day bites me since I don't type so quick.

      That doesn't have anything to do with quoting keys. $foo{name} will always be interpreted as $foo{'name'}, and there's no way you can disambiguate that by using or not using quotes.

      If that was supposed to call your name function, you should have written it with parens, as in $foo{name()}. In fact, you should get in the habit of never calling functions without parens. (And of using sub strictures.) That will disambiguate almost every case of possible confusion that crops up in Perl.

      Makeshifts last the longest.

Re: Correct keys in hashes
by TomDLux (Vicar) on Aug 30, 2004 at 01:54 UTC

    In Perl 6, acording to the currently most recent documents, bareword keys will be an error. That's why I have started quoting my hash keys. I want to be 18 months ( 36 months ) ( 48 months ) ahead of the rest of you.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://385641]
Approved by Corion
Front-paged by grinder
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2018-05-26 10:50 GMT
Find Nodes?
    Voting Booth?