我想和大家分享一下我創建的功能,以瞭解如何優化它,或者是否有更好的方法來實現這一點。你如何將密鑰,值對的散列平坦化?
sub flatten{
my($ref,$delim,$item_delim,$array,$str) = @_;
die("Required Hash Reference") unless isHash($ref);
$delim = $delim ? $delim :'_';
#dump into array hash vals #simplified
if(!$item_delim){
@{$array} = %{$ref};
}else{
my($keys,$values);
$keys = getKeys($ref);
$values = getValues($ref);
#item strings
if($#$keys > 0 && $#$values > 0){
#fix for issue where value[n] is empty
@{$array}= map{ (defined $$values[ $_ ]) ? $$keys[ $_ ].$item_delim.$$values[ $_ ] : $$keys[ $_ ].$item_delim } 0 .. int($#$keys);
}else{
log "No Values to flatten";
return '';
}
}
$str = join($delim,@{$array});
return $str;
}
有沒有我應該知道的優化點?
基本上我想從
$HASH => {
key1 => 'val1',
key2 => 'val2',
key3 => 'val3',
}
去$STRING= key1=val1&key2=val2 ...
修訂
沒有模塊解決方案是優選我真的只是想知道如何有效地拉平哈希!
請注意,這裏的一些函數只是簡單的包裝函數。 isHash getKeys ...不關注這些!
爲什麼你使用像'isHash','getKeys','getValues'這樣的函數?這是公司標準的一部分嗎?你可以不使用簡單的數組和哈希來代替引用嗎? – Borodin 2012-01-13 23:42:18