Damiii
Damiii

Reputation: 1373

Why am i getting an "Odd number of elements in anonymous hash " warning

I'm getting a warning in my perl code and don't know why...

Warning:

Odd number of elements in anonymous hash at /Users/../Tree.pm line 56.

Which gives me that line :

$dic->{$firstLetter}={$letra};

Is there a problem with the implementation?

I mean, it passes all the tests, but it's giving me these errors ... like 10 times always on the same line! Please, some advice will be welcome! :)

sub add_word{
    my ($self,$word) = @_ ;
    my $dic = $self->{'dic'};
    my @array = split(//,$word);
    my $firstLetter = shift @array;
    for my $letra(@array){
            if(!$dic->{$firstLetter}){
                    $dic->{$firstLetter} = {$letra};
                    $dic = $dic->{$firstLetter};
            }
            else{
                    if($dic->{$firstLetter}){
                            $dic = $dic->{$firstLetter};
                    }
            }
            $firstLetter = $letra;
    }
    $dic->{$firstLetter} = {"\$" => "\$"};
}

Upvotes: 7

Views: 10420

Answers (2)

friedo
friedo

Reputation: 66978

It's good that you have warnings turned on. When you use { ... } in an expression like {$letra}, you are constructing an anonymous hash reference. A hash wants to be initialized with key/value pairs. So when you write

$dic->{$firstLetter}={$letra};

That's almost the same as

my %anon = ( $letra );
$dic->{$firstLetter} = \%anon;

That hash will be messed up, because it has a key but no value. Thus, hashes want to have an even-sized list when they are constructed, so every key has a value. With an odd-size list as you have, it emits a warning.

My guess is you probably just want to assign a simple scalar. So try

$dic->{$firstLetter} = $letra;

And don't be afraid of the spacebar. :) It makes things easier to read.

Upvotes: 3

Quentin
Quentin

Reputation: 943615

= {$letra} is creating a hashref with a key but no value and trying to assign it.

You probably want to just assign the scalar you have:

$dic->{$firstLetter} = $letra;

Although you might want:

$dic->{$firstLetter} = { someKey => $letra };

or

$dic->{$firstLetter} = { $letra => "someValue" };

Upvotes: 7

Related Questions