Why does this not work

Why does this not give flinstone and rubble?

$fn{"fred"} = "flintstone";
$fn{"barney"} = "rubble";
foreach $per (qw< barney fred >) {
print " he's $per $fn($per).\n";
}

3 Comments

You're trying to get a hash value, but you are using parens instead of braces. You get:

 he's barney (barney).
 he's fred (fred).

Change your code to use braces for the single element access to the hash:

$fn{"fred"} = "flintstone";
$fn{"barney"} = "rubble";
foreach $per (qw) {
    print "he's $per $fn{$per}.\n";
    }

to get:

he's barney rubble.
he's fred flintstone.

Yep, like brian said. You access hash elements with $hash{"$key"}, $hash("$key") is you trying to access a referenced sub.

Also, go ahead and use "my %fn;" at the top so you know how your variable is scoped, what kind it is, and aren't assigning values to it before you know it exists. It will save you some crying in the future.

Finally, it's a bad idea to name a variable like it's a function. Leaving aside the fact that functions are called subs in perl, it's just confusing.

Leave a comment

About Eoin

user-pic I blog about Perl.