qod*_*nja -3 perl hash query-string
我想与你们分享我创建的一个函数,看看我如何优化它,或者是否有更好的方法来做到这一点.
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;
}
Run Code Online (Sandbox Code Playgroud)
我应该注意哪些优化点?
基本上我想要离开
$HASH => {
key1 => 'val1',
key2 => 'val2',
key3 => 'val3',
}
Run Code Online (Sandbox Code Playgroud)
至 $STRING= key1=val1&key2=val2 ...
更新
没有模块的解决方案是首选我真的只是想知道如何有效地压扁哈希!
请注意,这里的一些函数只是包装函数,可以完成他们所说的.isHash getKeys ...不注意那些!
一种方便的方法是使用URI的query_form工具.
use URI;
my $uri = URI->new("", "http"); # We don't actually care about the path...
$uri->query_form(%params);
my $query_string = $uri->query;
Run Code Online (Sandbox Code Playgroud)
另一种更手动的方法是使用URI :: Escape,map和join.
| 归档时间: |
|
| 查看次数: |
1542 次 |
| 最近记录: |