[Nh-pm] quoting list keys & values

Karl J. Runge runge at karlrunge.com
Fri Aug 2 10:01:56 CDT 2002


On Thu, 1 Aug 2002, Erik Price <erikprice at mac.com> wrote:

> %hash3 = (key => value);                 # unquoted key and value
> print "$hash3{key}\n";                   # unquoted key, prints: value
> print "$hash3{'key'}\n";                 # quoted key, prints: value

Be careful about barewords like "key" and "value" being interpreted
as builtin-functions or subroutines:

#!/usr/bin/perl

sub foo {
        return 'bar';
}

%hash = (time => time, foo => foo);	# time() is a perl builtin

foreach $k (keys %hash) {
        print "$k - $hash{$k}\n";
}

yields:

foo - bar
time - 1028299824


They appear to not be evaluated if it is the hash key, but not so for
the value...

In general I believe arbitrary expressions can be in either place:

$hash{ <expr1> } = <expr2>;

The only time I don't quote the bareword is when it is the hash key and
only contains word characters, e.g. $hash{foo_bar} = ... but no where else.

And I guess only do this because a Perl guru was code reviewing a
script of mine and said in *that* case it is OK and the bareword will not be
interpreted.  I've not read the docs about the scope of this feature,
usually tending to use the quotes to be safe.

Karl





More information about the Nh-pm mailing list