Search code examples
perllwp

decode form-urlencoded to hash


The response I get to an LWP request is application/x-www-form-urlencoded is it possible convert the text of this to a hash via some object method?


Solution

  • # from a HTTP::Response object
    my $urlencoded = $response->content;
    
    1. Vars in CGI returns a hash.

      use CGI qw();
      CGI->new($urlencoded)->Vars;
      
    2. parameters in Plack::Request returns a Hash::MultiValue object, which is actually the appropriate data structure for this.

      use Plack::Request qw();
      Plack::Request->new({QUERY_STRING => $urlencoded})->parameters;
      
    3. param in APR::Request/libapreq2 - not quite a Perl hash, but an XS object with attached Magic whose behaviour is close enough.

      insert hand-waving here, no libapreq2 available right now for testing
      
    4. url_params_mixed in URL::Encode

      require URL::Encode::XS;
      use URL::Encode qw(url_params_mixed);
      url_params_mixed $urlencoded;
      
    5. parse_query_string in CGI::Deurl::XS

      use CGI::Deurl::XS 'parse_query_string';
      parse_query_string $urlencoded;
      
    6. query_form in URI serves well, too, in a pinch; and so does query_form_hash in URI::QueryParam.

      use URI qw();
      URI->new("?$urlencoded")->query_form;
      
      use URI::QueryParam qw();
      URI->new("?$urlencoded")->query_form_hash;
      
    7. Bonus: also see HTTP::Body::UrlEncoded, as used by Catalyst.