【发布时间】:2011-01-31 02:57:16
【问题描述】:
这是我第一次以这种方式操作哈希和数组——而且它正在工作。基本上,对于每个键,我都想记录多个值,然后以“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.
}
【问题讨论】:
-
你真的应该在
use strict; use warnings;模式 -
哎呀,这产生了一个邪恶的警告列表。我将不得不通过它们。
-
我希望真实的代码没有这么多的cmets。
-
我很惊讶没有人向您指出 Data Structures Cookbook,又名 perldoc perldsc - perldoc.perl.org/perldsc.html 许多示例。
-
不,真正的代码没有这么多的cmets。 :) 谢谢你的食谱链接!