newspaint

Documenting Problems That Were Difficult To Find The Answer To

The Perl Hash Assignment Gotcha

Question: what do you get if you run the following Perl script?

use warnings;

my %hash => (
    'name' => 'Jimmy',
);

Answer: you get the message:

Useless use of a constant (name) in void context at hashtest.pl line 3.
Useless use of a constant (Jimmy) in void context at hashtest.pl line 3.

So what went wrong? The answer is simple enough but very easy to miss. You probably wanted to assign to the hash variable – but used the comma operator (=>) instead.

To fix merely use an equals sign only after declaring the hash variable:

use warnings;

my %hash = (
    'name' => 'Jimmy',
);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: