• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 285
  • Last Modified:

Sorting form pairs in perl

I am parsing form pairs from a web form, but can not figure out how to then sort them alphabetically.  Here is the code I am using below.

I have tried   @form = sort @form;
but that doesn't seem to work.  


sub form_parse  {
      read (STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
      @pairs = split(/&/, $buffer);

      foreach $pair (@pairs)
          ($name, $value) = split(/=/, $pair);
          $value =~ tr/+/ /;
          $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
          $form{$name} = $value;
2 Solutions
You should use the CGI module to parse the form.

But that aside:
You have a hash %form, this is a completly different variable from @form.
If you want to get the keys sorted:
@keys = sort keys %form.
To expand on Adam's comments.

Only use your own CGI parser if you are 101% familiar with the full CGI specifications and all the various gotchas from none compliant browsers and web servers.

The standard Perl CGI module takes all of this into account.

The code for doing the sorting would be:

use strict;
use CGI;
my $q = new CGI;
my @keywords = sort $q->param;
print $q->header('text/plain');
foreach my $key (@keywords) {
  print "Keyword: $key\n";

Open in new window

webcsAuthor Commented:
Adam I inserted

@keys = sort keys %form;

at the end and it didn't change the order at all.
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

It doesn't change %form, but it changes @keys
What are you doing with @keys and %form that did not change?
perldoc -q "sort a hash"
ans perhaps
perldoc Tie::IxHash
webcsAuthor Commented:
Ok your replies led me in the right direction, as I just looked up HASH sort and got lots of info on google.

Ended up using this:

      foreach $key (sort keys %form) {
         # Print the name and value pairs in FORM array to MAIL.
         print MAIL "$key: $form{$key}";

Thanks for the help.  For everyone reference that sorts alphabetically upwards on the key.  thanks
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now