如何查看Perl哈希是否已经具有某个键? [英] How can I see if a Perl hash already has a certain key?

查看:660
本文介绍了如何查看Perl哈希是否已经具有某个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Perl脚本,该脚本正在计算文本文件中各种字符串的出现次数.我希望能够检查某个字符串是否还不是哈希中的键.有没有更好的方法可以完全做到这一点?

I have a Perl script that is counting the number of occurrences of various strings in a text file. I want to be able to check if a certain string is not yet a key in the hash. Is there a better way of doing this altogether?

这是我在做什么:

foreach $line (@lines){
    if(($line =~ m|my regex|) )
    {
        $string = $1;
        if ($string is not a key in %strings) # "strings" is an associative array
        {
            $strings{$string} = 1;
        }
        else
        {
            $n = ($strings{$string});
            $strings{$string} = $n +1;
        }
    }
}

推荐答案

我相信要检查您刚刚执行的哈希中是否存在键

I believe to check if a key exists in a hash you just do

if (exists $strings{$string}) {
    ...
} else {
    ...
}

这篇关于如何查看Perl哈希是否已经具有某个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆