简体   繁体   中英

A simple hashing-array-loop, I get error warnings even though it works, why is that?

I have prepared a short loop that looks like this:

@array = ("a", "b", "c", "d", "e");
$count=0;
print "@array\n";
foreach $string(@array){
    $number=$count++ +1 ;
    $string{$link} = $number;
    print "$string\n$string{$link}\n";
}

It should come out as

a
1
b
2

... and so on. It works but when I print it out on the terminal, I get warning messages:

Use of uninitialized value $link in hash element at ./hashing_an_array.pl line 11.
Use of uninitialized value $link in hash element at ./hashing_an_array.pl line 12.
a
1
Use of uninitialized value $link in hash element at ./hashing_an_array.pl line 11.
Use of uninitialized value $link in hash element at ./hashing_an_array.pl line 12.
b
2

...

etc

Why do I get these messages? I just wanted to know so that even though it works, I am sure I know what I am doing.

It happens because you never assigned a value to $link so it's default value is undef. Trying to use undef as a hash key generates a warning message because it's invalid.

Read perldata http://perldoc.perl.org/perldata.html

As noted in the other answers $link is undeclared and you should use strict; which would tell you this:

Global symbol "$link" requires explicit package name (did you forget to declare "my $link"?)

The following snippet is probably something like what you were after:

#!/usr/bin/perl

use strict;
use warnings;

my @array = qw(a b c d e);

my $count = 0;

my %link;

foreach my $string (@array) {
    $count++;
    $link{$string} = $count;
    print "$string\n";
    print "$link{$string}\n";
}

Although you should probably rename your hash and iteration variable to something that better reflects your intent, like for example using %count_for and $letter if you were doing letter counts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM