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

Str*_*ure 5 arrays perl hash

这是我第一次以这种方式操纵哈希和数组 - 它正在运行.基本上,对于每个键,我想要记录多个值,然后以"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.
}
Run Code Online (Sandbox Code Playgroud)

mar*_*usk 2

以下代码与您的代码执行相同的操作,没有不必要的步骤。

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.
}   
Run Code Online (Sandbox Code Playgroud)

然而,正如其他人评论的那样,在大多数情况下应该避免全局变量。相反,列表键和列表值的词法作用域应为my(),并且用于生成列表值的函数应采用一个或多个参数(域、列表键和/或列表值)作为输入。

线条

$list{$listkey} = ++$i unless $list{$listkey};
$list{$listkey} = [] unless exists $list{$listkey};
Run Code Online (Sandbox Code Playgroud)

在您的原始代码中不需要,push @{ $list{$key} }, $value初始化一个条目就足够了。