2

I am working on some tutorials to explain things like GET/POST's and need to parse the URI manually. The follow perl code works, but I am trying to do two things:

  1. list each key/value
  2. be able to look up one specific value

What I do NOT care about is replacing the special chars to spaces or anything, the one value I need to get should be a number. In other languages I have used, the regular expression in question should group each key/value into one grouping with a part 1/part 2, does Perl do the same? If so, how do I put that into a map?

my @paramList = split /(?:\?|&|;)([^=]+)=([^&|;]+)/, $ENV{'REQUEST_URI'};
if(@paramList)
{
    print "<h1>The Params</h1><ul>";
    foreach my $i (@paramList) {
        if($i) {
        print "<li>$i</li>"; 
        }
    }
    print "<ul>";
}

Per the request, here is a basic example of the input:

REQUEST_URI = /cgi-bin/printenv_html.pl?customer_name=fdas&phone_number=fdsa&email_address=fads%40fd.com&taxi=van&extras=tip&pickup_time=2020-01-14T20%3A45&pickup_place=&dropoff_place=Airport&comments=

goal is the following where the left of the equal is the key, and the right is the value:

customer_name=fdas
phone_number=fdsa
email_address=fads%40fd.com
taxi=van
extras=tip
pickup_time=2020-01-14T20%3A45
pickup_place=
dropoff_place=Airport
comments=
3
  • It'd be nice to see a sample of that ENV variable (and s0 why/how split is needed) ? Commented Jan 25, 2020 at 22:14
  • can do, I have added that to the post. Commented Jan 25, 2020 at 22:21
  • Thank you, got it -- edited my answer ... still checking ... is that what you need? Commented Jan 25, 2020 at 22:22

1 Answer 1

3

How about feeding your list of key-value pairs into a hash?

my %paramList = $ENV{'REQUEST_URI'} =~ /(?:\?|&|;)([^=]+)=([^&|;]+)/g;

(no reason for the split as far as I can tell)

This relies crucially on there being an even-sized list of matches, where each "before-=" thing becomes a key in the hash, with the value being its pairing "after-=" thing.

In order to also get "pairs" without a value (like comments=) change + in the last pattern to *

Sign up to request clarification or add additional context in comments.

2 Comments

The only tweak was to my regex, needed to change the final + to * to also capture the ones that do NOT have values, all is good, thank you!
@SamCarleton Right! Just noticed that, tested, and updated with a comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.