3

I tried this code. This isn't working. I am getting no result at output. What mistake am I making?

my %fruit_color = ("apple", "red", "banana", "yellow");
my @fruits = keys %fruit_colors;
my @colors = values %fruit_colors;
print @fruits;
print @colors;

Codepad link: http://codepad.org/vDVAxJcp

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133

5 Answers5

9

You're declaring fruit_color but referencing fruit_colors (notice the trailing S)

You would have noticed this had you used warnings and stricture.

use warnings;
use strict;


Global symbol "%fruit_colors" requires explicit package name at C:\temp\test.pl line 4.
Global symbol "%fruit_colors" requires explicit package name at C:\temp\test.pl line 5.
Ed Guiness
  • 34,602
  • 16
  • 110
  • 145
7

The first mistake is not having this as the first lines:

use strict;
use warnings;

Second, you have a typo ( which would have been easier to spot if you had been using the strict module ).

Geo
  • 93,257
  • 117
  • 344
  • 520
4

Man, you people are quick.

As others have stated:

  • You created a list with one name, but then referenced it to another.
  • If you used use warnings and use strict, you would have gotten an error message telling you about the error.

There are lots of hints and tricks to writing legible and relatively bug free Perl code. For example, I don't use plurals in variable names. Thus, if it's a question of "fruit" or "fruits", I know it should be "fruit". I also tend to say the name of my data types by using terms like "fruitColorHash" vs. "FruitColorList" even though (Camel Casing isNotInStyleAnyMore, but then Im_an_old_grouchy_developer_who_is_set_in_his_ways).

Damian Conway's book Perl Best Practices is an excellent book that will help you learn all of those tricks and tips that will help you avoid issues like this. In fact, the book is considered such a touchstone of good Perl programming, that there's now an entire section devoted to Damian Conway's book called Perlstyle, and a program called tidyperl that will help reformat and point out places that don't follow Conway's examples.

So, go ahead and look at the Best Practices section in Perldoc (You know about the perldoc documentation, don't you? Type in the command perldoc and see what you get) and absorb the knowledge placed there in. Then get Conway's book.

David W.
  • 105,218
  • 39
  • 216
  • 337
3

You have a typo in your code, which you would have noticed if you had had:

use warnings;
use strict;

in your code. Which you always should.

TLP
  • 66,756
  • 10
  • 92
  • 149
1

You have a typo:

my %fruit_color = ("apple", "red", "banana", "yellow");

should be

my %fruit_colors =  ("apple", "red", "banana", "yellow");
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72