【问题标题】:Error for hash variable while accessing after assigning value in for loop在for循环中分配值后访问哈希变量时出错
【发布时间】:2014-06-04 19:28:45
【问题描述】:

我在 for 循环之外定义了一个哈希变量

my %sports = (); #hash variable defined
my $count = 0; #key for the hash variable which will be used to populate the hash 

在 for 循环中,我通过一些逻辑填充了这个变量

$sports{$count} = "cricket"
$count++;

现在,当我尝试在循环外打印映射到此哈希变量的所有值时,出现错误

我输入了

print $count." -->  ".$sports{$count}  ; 

我得到一个错误

在连接 (.) 或 %sports 中使用未初始化的值 字符串在

【问题讨论】:

  • 看起来你真的想要一个数组。
  • 你在分配后少了一个分号:$sports{$count} = "cricket";当人们甚至不尝试运行他们发布的代码时,我很难过......SSCCE

标签: perl hash


【解决方案1】:

而不是,

$sports{$count} = "cricket"
$count++;

试试

$count++;
$sports{$count} = "cricket"

所以你的$count 将保存最后使用的%sports 散列密钥。

【讨论】:

    【解决方案2】:

    在最后一次赋值之后,您增加了 $count 的值。因此,%sports 哈希中不存在新值。使用

    print $count - 1, ' -->  ', $sports{ $count - 1 };
    

    此外,如果您使用数字序列作为哈希键,您可能会切换到数组。

    【讨论】:

      【解决方案3】:

      要打印映射到哈希的所有值,请遍历键:

      for my $count (keys %sports) {
          print $count." -->  ".$sports{$count};
      }
      

      【讨论】:

        【解决方案4】:

        错误是因为您试图访问未分配的哈希值。

        你的迭代是这样的

        $count = 0
        
        # Lets say loop goes from 0 to 5.
        # So, when $count = 5 
            $sports{$count} = "cricket"
            $count++;  # Here $count becomes 6 and loop ends
        
        print $sports{$count}  # Outside loop, Here $count is still 6, you are
                               # trying to print $sports{6}, which is unassigned
        

        你需要把$count++移到前面

        $count++;
        $sports{$count} = "cricket"
        

        【讨论】:

          猜你喜欢
          • 2015-07-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多