你如何压扁键值对的散列?

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 ...不注意那些!

hob*_*bbs 6

一种方便的方法是使用URIquery_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.

  • @nodebunny如果你在奇怪的限制下工作,你应该在你的问题中提到它们.如果您不愿意使用该模块,请访问http://search.cpan.org/perldoc?URI并查看源代码并获取所需内容. (2认同)