Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use $hash{"string"} or $hash{string} in Perl?

In Perl, which of these is the "better" style?

$hash{"string"} or $hash{string}?

In any case, are they functionality identical?

like image 913
Jessica Avatar asked Sep 23 '09 23:09

Jessica


3 Answers

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 ;-)

like image 150
draegtun Avatar answered Oct 20 '22 03:10

draegtun


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.

like image 21
Artem Russakovskii Avatar answered Oct 20 '22 04:10

Artem Russakovskii


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.)

like image 31
jrockway Avatar answered Oct 20 '22 05:10

jrockway