Dave's Brain

Browse - Programming Tips - How do I get a hash of the perl CGI variables?

Date: 2010feb11
Language: perl
Platform: web

Q.  How do I get a hash of the perl CGI variables?

A.  Here's how you do that and some other handy perl CGI functions.

# Returns has hash of the CGI variables sub getHash($) { my($q) = @_; return $q->Vars; } sub exampleUse() { my($q, %h, $thing); $q = new CGI; %h = getHash($q); $thing = $h{thing}; } #--------------------------------------------- sub getNames($) { my($q) = @_; return $q->param; } sub exampleUse() { my($q, $i); $q = new CGI; for $i (getNames($q)) { print "$i\n"; } } #--------------------------------------------- sub isSSL($) { my($q) = @_; my($url); return $q->url() =~ m/^https:/i; } sub exampleUse() { my($q); $q = new CGI; if (!isSSL($q)) { print "Not secure\n"; return; } } #--------------------------------------------- sub ensureSSL($) { my($q) = @_; if (!isSSL($q)) { my($url); $url = $q->url(); $url =~ s/http:/https:/; print qq(<meta http-equiv="refresh" content="0; url=$url">); return 0; } return 1; } sub exampleUse() { my($q); $q = new CGI; return if !ensureSSL($q); } #--------------------------------------------- # Does the same as CGI::query_string() but with &'s sub getQueryString($) { my($q) = @_; my($i, $qs); for $i (getNames($q)) { if ($qs) { $qs .= '&'; } $qs .= $i . '=' . $q->param($i); } return $qs; }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.