Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

using quotes in hash keys

by thefid (Friar)
on Mar 27, 2001 at 02:20 UTC ( [id://67355]=perlquestion: print w/replies, xml ) Need Help??

thefid has asked for the wisdom of the Perl Monks concerning the following question:

I often see examples of straight values (excluding single & double quotes) as keys for hashes and most recenlty saw in Advanced Perl Programming, ex 2-3 (p 30) of
$curr_prof->{Office Hours} = interval_parse($1);
I receive an error when I try and test the code: Can't locate object method "Office" via package "Hours". At first I thought it must be an error that Sriram left out the quotes, but I could not find it in the errata I always use quotes or string variables as keys and will continue to do so, but is the above code an error or not? Further testing:
$baseball_team{Seattle} = "Mariners";
okay!
$baseball_team{Los Angeles} = "Dodgers";
error!
$la = "Los Angeles"; $baseball_team{$la} = "Dodgers";
okay!

Replies are listed 'Best First'.
(jeffa) Re: using quotes in hash keys
by jeffa (Bishop) on Mar 27, 2001 at 02:23 UTC
    or simply:
    $baseball_team{'Los Angeles'} = 'Dodgers';
    You have to place the literal in quotes if it contains white space or other characters that confuse the compiler.

    Futher example, these are not the same:

    # example 1 $you_never_give_me_any{$money}; # key equals value of $money # example 2 $you_never_give_me_any{'$money'}; # key equals literal string '$mone +y' # example 3 $you_never_give_me_any{"$money"}; # key equals value of $money
    Jeff

    R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
    L-L--L-L--L-L--L-L--L-L--L-L--L-L--
    
      If you'll forgive the some what philosophical bent,.... I find it useful to remind myself on occasion that I'm not actually writing the program. Rather I am creating a set of communications (i.e. commands) which some poor compiler or interpreter is slated to execute. Hence if something is ambiguious it's not surprising that the interpreter burps. Perl is actually one of the most forgiving languages I've had the pleasure to work with. Even my oft-time idiotic code gets the job done. ;-) Claude
Re: using quotes in hash keys
by tadman (Prior) on Apr 24, 2001 at 19:42 UTC
    This is certainly an 'Advanced' trick. It is probably best to quote everything until you know what can go without, as there are some surprising things that can crop up once in a while, especially if you're brave enough to use Perl without '-w' or 'strict'.

    As an introduction, though, there are a number of contexts where Perl is smart enough to recognize 'strings' even though they are not explicitly inside of quotes. This holds true even under '-w' and 'strict', which are extremely bitter about so-called bare-words, or ambiguous strings, and they will fiercely protest if given an opportunity.

    A "safe string" is composed of one or more alphanumeric characters, with underscore also available, but the first character has to be a letter or a dash. You could define this as a regular expression: /\-?[A-Za-z_][A-Za-z0-9_]*/.

    So, here are some examples:
    Safe Unsafe ------------------------------------------ foo foo bar -foo --foo foo_bar foo+bar jane3 3jane
    If you get too ambitious, Perl might think you're making a subroutine reference (i.e. &foo), or are trying to reference an internal function (i.e. delete) In a hash context, for example, Perl "knows" what you mean when you leave a bare 'safe string'. You might do this inside a hash definition:
    my (%hash) = ( key_1 => 'value1', key_2 => 'value_2' ); print $cgi->textfield(-name => 'input1');
    Or, inside a hash reference:      $hash{key_3} = 'value3'; The same sort of trick applies to where quotation is required in HTML, as you can often get away with no quotes at all if you stick to letters and numbers only.

    If you have a syntax-highlighting editor, you can actually see the parser change highlighting when you type '=>' after a "safe string", as it now realizes what you mean.
      A "safe string" is composed of one or more alphanumeric characters, with underscore also available, but the first character has to be a letter or a dash. You could define this as a regular expression: /\-?A-Za-z_A-Za-z0-9_*/.
      What about letters outside the ASCII range? Perl allows Unicode letters as variable names, for example. Do barewords here get the same treatment? $α{niņa}=5;
        If anyone had the official "lex" specification for hash keys, it would be very enlightening. A "valid" string is probably a broader definition then my very conservative "safe" string specification.

        Update:
        I am implying that this would be found in the Perl source code (in a .lex file, perhaps?)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://67355]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-04-24 16:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found