in reply to using quotes in hash keys

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.

Replies are listed 'Best First'.
Re: Re: using quotes in hash keys
by John M. Dlugosz (Monsignor) on Jul 07, 2001 at 21:45 UTC
    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?)
        You could look in the Perl source code. Testing whether a bareword is not a warning/error is probably not in the grammar, though, but in logic applied later.