检查哈希键是否存在会创建密钥

检查哈希键是否存在会创建密钥

本文介绍了检查哈希键是否存在会创建密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

给出以下代码

#!/usr/bin/perl

use Data::Dumper;

my %hash;
my @colos = qw(ac4 ch1 ir2 ird kr3);

foreach my $colo (@colos) {
    if(exists $hash{output}{$colo}) {
        print "$colo is in the hash\n";
    }
}

print Dumper(\%hash);

我创建了一个空哈希.我有一个数组,里面有一些缩写.如果我遍历数组以查看这些家伙是否在哈希中,则不会向STDOUT显示任何内容,但是出于某种原因会创建$ hash {output}.这根本不符合逻辑.我正在做的只是一个if存在.我哪里出问题了?

I have an empty hash that is created. I have an array with a few abbreviations in it. If I cycle through the array to see if these guys are in the hash, nothing is displayed to STDOUT which is expected but the $hash{output} is created for some reason. This does not make sense. All I am doing is an if exists. Where did I go wrong?

推荐答案

exists在给定哈希中查找哈希元素.您的代码正在自动生成哈希
%{ $hash{output} }并检查该哈希中是否存在键为$colo的哈希元素.

exists looks for a hash element in a given hash. Your code is autogenerating the hash
%{ $hash{output} } and checking if a hash element with key $colo is existing in that hash.

请尝试以下操作:

if(exists $hash{output}{$colo}) {

更改为

if(exists $hash{output} and exists $hash{output}{$colo}) {

您当然可以编写一个隐藏代码中复杂性的子程序.

You can, of course, write a sub that is hiding that complexity from your code.

这篇关于检查哈希键是否存在会创建密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:27