
我的代码如下.我很惊讶它有效,因此担心它会“误 *** 作”.这是完成此任务的正确方法,还是有更有效或更合适的方法?
while ($source =~ m/(regex)/g) { #Get all key names from source $Listkey = ; #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 = ; # 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即可初始化一个条目.
总结以上是内存溢出为你收集整理的这是构建利用数组的Perl哈希的正确方法吗?全部内容,希望文章能够帮你解决这是构建利用数组的Perl哈希的正确方法吗?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)