2
$color_of{apple} = "red";
print $color_of{apple}; 

The above code is printing red when I have not even initialized the hash. Is this allowed in perl and will it always compile?

I can't remember the exact code but once I got the following error when the map wasn't initialized explicitly.

Global symbol "%map" requires explicit package name at ....

Code link : http://ideone.com/NJDTUj

xxfelixxx
  • 6,512
  • 3
  • 31
  • 38
Nikunj Banka
  • 11,117
  • 16
  • 74
  • 112

1 Answers1

6

You get that error when you use strict, which you should always do. You should also always use warnings to turn warnings on.

It is considered good practice and called Modern Perl (which is everything more or less after Perl 5.08, don't quote me on that) to always have strict and warnings. They make sure you don't have stupid mistakes, enforce that you declare variables, tell you about declaring them twice and so on.

So the answer is, you do not need to declare* any kind of variable in Perl, but you should do it anyway. Frankly, if you work with other people, those will hate you if you don't.

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';

my %color_of; # no need to put () unless you explicitly want an empty list
$color_of{apple} = 'red';

say $color_of{apple};

*) Declaring a variable means you tell Perl that there is a variable. You do that with my, which makes a lexical variable that only lives inside a block (like a sub, or inside of the curly braces of if (1) { ... }. Initializing a variable means to give it a value before you use it. Usually that is done at the same time as declaring it in Perl. If you do not do that, the variable will be undef, which is perfectly fine.


An even stricter approach is to use strictures, which you need to install from CPAN.

simbabque
  • 53,749
  • 8
  • 73
  • 136
  • Would suggest differentiating between 'declaring' and 'initializing'. The OP asks about the latter, but seems to mean the former. Declaring is necessary under strict. Initializing isn't. – Sobrique Jul 20 '15 at 11:39
  • @Sobrique: better? :) – simbabque Jul 20 '15 at 11:43