CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Advanced:
Non-Order regexp to order output??

 



perldood
stranger

Oct 10, 2001, 6:41 AM

Post #1 of 3 (1153 views)
Non-Order regexp to order output?? Can't Post

Question -- I would like to search a url which has elements in indeteminate order, however have the results stored in particular order. I've read up on ZeroWidth and backtracking, however just need a pointer in the right direction.

For instance:
/some/dir/blah.html?hair=black&car=blue&eyes=green
/some/dir/blah.html?car=blue&eyes=green&hair=black
/some/dir/blah.html?car=blue&eyes=green&hair=black

they should all output to
/new/dir/foo.html?field=\1&field=\2&field=\3

whereby \1 is car \2 is hair \3 is eyes for all urls.

any ideas?

thx



perldood
stranger

Oct 11, 2001, 6:24 AM

Post #2 of 3 (1142 views)
Re: Non-Order regexp to order output?? [In reply to] Can't Post

Just a followup to my question: I need to have the
assignment within the regular expression, because
of a third party software.

thx



brentdax
stranger

Oct 23, 2001, 2:22 AM

Post #3 of 3 (1128 views)
Re: Non-Order regexp to order output?? [In reply to] Can't Post

Regexps aren't really very well suited for this sort of thing, unfortunately, so you have to use a more complicated solution

This is gonna be really ugly-looking, but it ought to work:


Code
#assume the text we're parsing is in $string 
my %stuff=map {split '='} split '&', ($string =~ /\?(.*)$/);
#now use the contents of %stuff to generate the new string, like:
$newstring="/new/dir/foo.html?car=$stuff{car}&eyes=$stuff{eyes}&hair=$stuff{hair}";

Here's how it works: the regular expression grabs everything between the first question mark and the end of the string. In your example, at this point we would be dealing with

Code
"hair=black&car=blue&eyes=green"

. Next, we split that on & signs, leaving us with the list

Code
("hair=black", "car=blue", "eyes=green")

. Then we use map to apply another split, this time on equals sign, to that list, yielding the list

Code
("hair", "black", "car", "blue", "eyes", "green")

. This is exactly like

Code
("hair" => "black", "car" => "blue", "eyes" => "green")

, which gets put into the hash %stuff. Now %stuff has the names of the fields as keys and the values of those fields as values. Not too hard, is it? :^)

Brent Dax
brentdax@cpan.org

"When I take action, Iím not going to fire a $2 million missile at a $10 empty tent and hit a camel in the butt." --Dubya

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives