加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

这是构建利用数组的Perl哈希的正确方法吗?

发布时间:2020-12-16 06:24:50 所属栏目:大数据 来源:网络整理
导读:这是我第一次以这种方式操纵哈希和数组 – 它正在运行.基本上,对于每个键,我想要记录多个值,然后以“key – value – value – val …”的形式打印出来. 我的代码如下.我很惊讶它有效,因此担心它会“误操作”.这是完成此任务的正确方法,还是有更有效或更合适
这是我第一次以这种方式操纵哈希和数组 – 它正在运行.基本上,对于每个键,我想要记录多个值,然后以“key – > value – > value – > val …”的形式打印出来.

我的代码如下.我很惊讶它有效,因此担心它会“误操作”.这是完成此任务的正确方法,还是有更有效或更合适的方法?

while ($source =~ m/(regex)/g) { #Get all key names from source
    $listkey = $1; #Set current list key to the current regex result.
    $list{$listkey} = ++$i unless $list{$listkey}; #Add the key to the hash unless it already exists.
    $list{$listkey} = [] unless exists $list{$listkey}; #Add an array for the hash unless the hash already exists.
    while ($loopcount==0) {
            if ($ifcount==0) {
                    $listvalue=result_of_some_function_using_list_key; #Get the first list value by using the list key.
                    $ifcount++; #Increment so we only get the first list value once.
            } else {
                    $listvalue=result_of_some_function_using_list_value; #Update the list value by using the last list value.
            }
            if ($listvalue) { #If the function returned a value...
                    push @{$list{$listkey}},$listvalue; #...then add the value to the hash array for the key.
            } else { #There are no more values and we need a new key.
                    $listkey=0; #Reset variable.
                    $listvalue=0; #Reset variable.
                    $loopcount++; #Increment loop counter to exit loop.
            }
    }
$ifcount=0; #Reset count variable so the next listvalue can be generated from the new key.
    $loopcount=0; #Reset count variable so another loop can begin for a new key.
}
foreach $listkey (keys %list) { #For each key in the hash.
    print "$listkey --> "; #Print the key.
    @values = @{$list{$listkey}}; #Reference the arrays of the hash.
    print join ' --> ',@values; #Print the values.
    print "n"; #Print new line.
}

解决方法

以下代码与您的代码相同,没有不必要的步骤.

while ($source =~ m/(regex)/g) { # Get all key names from source
    $listkey = $1;            # Grab current regex result.
    $listvalue = result_of_some_function_using_list_key;
    while ($listvalue) {
        push @{$list{$listkey}},$listvalue; 
        $listvalue = result_of_some_function_using_list_value;
    }
    $listkey = 0;                # Reset variable.
    $domain = 0;                 # Reset variable.
}

但是,正如其他人所评论的那样,在大多数情况下应该避免全局变量.相反,列表键和列表值应使用my()进行词法范围限定,并且用于生成列表值的函数应将一个或多个参数(域,列表键和/或列表值)作为输入.

线条

$list{$listkey} = ++$i unless $list{$listkey};
$list{$listkey} = [] unless exists $list{$listkey};

在原始代码中不需要,只需按@ {$list {$key}},$value即可初始化一个条目.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读