【问题标题】:Using a variable as a hash key Perl 5.32使用变量作为哈希键 Perl 5.32
【发布时间】:2021-03-01 17:27:37
【问题描述】:

我正在从 csv 文件中读取用户 ID 并尝试检查该用户 ID 是否存在于我的哈希中,但是我发现我通过 if(exists($myUserIDs{"$userID"})) 进行的检查永远不会返回 true,尽管我使用了我的多个密钥进行了测试哈希。

open $file, "<", "test.csv";
while(<$file>)
{
    chomp;
    @fields = split /,/, $_;
    $userID = @fields[1];
    
    if(exists($myUserIDs{"$userID"}))
    {
        #do something
    }
}

【问题讨论】:

  • 也许您想使用$fields[1]?
  • $myUserIDs{"$userID"} 是写$myUserIDs{$userID} 的一种过于复杂的方式。引号字符是不必要的。
  • 在 if 之后尝试添加:else { print "Not found [$userID]\n"; } - 在用户 ID 周围加上方括号很重要,因为它可以使某些问题变得明显,例如 $userID 是否有前导或尾随空格。

标签: perl


【解决方案1】:

原来我写了我的测试 csv 文件,每个逗号后都有空格。 像 1, 2, 3 而不是 1,2,3 所以我的键实际上并不匹配。我有一个小时的时间哈哈。

【讨论】:

    【解决方案2】:

    看看这是否适合你。

    use strict; use warnings;
    use Data::Dumper;
    
    my (%myUserIDs, @fields);
    %myUserIDs = (
                    '1' => 'A',
                    '4' => 'D'
                );
    
    print Dumper(\%myUserIDs);
    
    while(<DATA>)
    {
        chomp;
        @fields = split /,/, $_;
        my $userID = $fields[1];
        
        if(exists($myUserIDs{$userID})){
            print "ID:$userID exists in Hash\n";
        } else {
            print "ID:$userID not exists in Hash\n";
        }
    }
    
    __DATA__
    A,1
    B,2
    C,3
    

    输出:

    $VAR1 = {
              '4' => 'D',
              '1' => 'A'
            };
    ID:1 exists in Hash
    ID:2 not exists in Hash
    ID:3 not exists in Hash
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-16
      • 2013-08-26
      • 1970-01-01
      • 2013-01-16
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多