In Perl, which of these is the "better" style?
$hash{"string"} or $hash{string}?
In any case, are they functionality identical?
From perldata perldoc:
In fact, an identifier within such curlies is forced to be a string, as is any simple identifier within a hash subscript. Neither need quoting. Our earlier example,
$days{'Feb'}
can be written as$days{Feb}
and the quotes will be assumed automatically. But anything more complicated in the subscript will be interpreted as an expression. This means for example that$version{2.0}++
is equivalent to$version{2}++
, not to$version{'2.0'}++
So yes fundamentally identical. However beware of gotchas:
sub is_sub { 'Yep!' }
my %hash;
$hash{ is_sub } = 'Nope';
$hash{ is_sub() } = 'it is_sub!!';
say Dumper \%hash;
Will show:
$VAR1 = { 'is_sub' => 'Nope', 'Yep!' => 'it is_sub!!' };
My preference is for the bareword... but remember those () or a preceding + (see jrockway's comment and answer) if you're calling a sub ;-)
They're functionally identical, that is until your key has a space or some other non-alphanumeric character in it. Then you have to use the quoted approach.
I prefer to not quote and use names that contain alpha_num and the underscore. That lets me get away with not quoting most of the time.
Avoiding the quotes is more idiomatic.
Edit to add:
Quoting is not the solution to absolute readability. Consider the inconsistency here:
sub function() { 'OH HAI' }
my @list = ('foo', 'bar', function);
# ==> ('foo', 'bar', 'OH HAI')
my %hash;
$hash{'foo'} = 1;
$hash{'bar'} = 2;
$hash{function} = 3;
# ==> { foo => 1, bar => 2, function => 3 } (oops)
When you never quote strings, the "weird" things are visually different from the plain strings... and it is parsed correctly.
$hash{foo} = 1;
$hash{bar} = 2;
$hash{+function} = 3; # aha, this looks different... because it is
# ==> { foo => 1, bar => 2, 'OH HAI' => 3 }
(Stack Overflow's syntax highlighting messes this up, so try to ignore it.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With