Forum Moderators: coopster & phranque

Message Too Old, No Replies

Parsing x-www-form-urlencoded data

A call for one liners - a general solution for using map to build hashes

         

andreasfriedrich

6:28 pm on Feb 5, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



POSTed data is submitted x-www-form-urlencoded as the body of the HTTP request method. To get the data into a hash I used this line:


my %data = map {split(/=/, $_)} split /&/, $request->content;

This will break when there is a key that does not have a value associated with it. This is a general problem when using map to build a hash. You need to make sure that the code in curly braces returns a list with two elements. How do you solve that problem?

Of course one could simply check for that, but doing so will not fit into that one line. Hereīs what I came up with:


my %data = map {(split(/=/, $_), '')[0,1]} split /&/, $request->content;

Do you have any better ideas.

Andreas

the_Eych

7:22 pm on Feb 5, 2003 (gmt 0)

10+ Year Member



Greetings, Adreas.

This one is a little bit shorter and seems to be working too:


my %data = map {(split(/=/, $_))[0,1]} split /&/, $request->content;

Sergey

andreasfriedrich

7:26 pm on Feb 5, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld [webmasterworld.com] Sergey.

Be sure to read Marcia`s wonderful WebmasterWorld Welcome and Guide to the Basics [webmasterworld.com] post.

Thatīs nice. So Perl will create the missing element in the list on the fly when it is needed. Itīs always so helpful and considerate. Everything just magically comes into existence when it is needed.

Andreas