Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

hash

perl

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} = {"\$" => "\$"};
}
like image 244
Damiii Avatar asked Nov 24 '13 21:11

Damiii


2 Answers

= {$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" };
like image 83
Quentin Avatar answered Nov 17 '22 23:11

Quentin


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.

like image 36
friedo Avatar answered Nov 17 '22 23:11

friedo