At 11:01 03.07.2001 +0200, Martijn van Exel wrote:
>Dear subscribers,
>
>I was in a modular mood and thought it might just be a good idea to do the 
>parsing of the querystring in a subroutine. The subroutine goes into a 
>separate file that I then 'require' in all my future CGI-scripts (is this 
>a good way?).
>
>I thought it would be nice to return a hash with the key/value pairs from 
>my querystring. I was thinking of the following:

That's a good idea, though you will be urged by the list to use CGI.pm 
which already does that (and much more) for you.  I personally don't use 
CGI.pm, because I don't see a need to load up the entire module when I only 
want to get the query string.  So, I have a function in my own HTML module 
which returns the query string in a hash ref.  I recommend using a module, 
not a require.

>sub parseit
>{
>         foreach $name ($q->(param))
>         {
>                 $input{$name} = $q->param($name);
>         }
>         return \%input;
>}
>
>Because a subroutine cannot return a hash (or so I was told) I instead 
>return a reference to the hash. I'm not sure if this will work. How would 
>I access the data in my main cgi? Or am I making things more difficult 
>than they should be?

Yes, subroutines can return a hash, or an array, or a string, or whatever 
you want.  Efficient practice dictates that you pass references around, so 
that you're not making copies of arrays and hashes all over the place, 
which slows you down.  I've gotten so used to refs, that I rarely bother 
with arrays or hashes anymore, and declare them all as refs right from the 
beginning.  In the end, it's the same thing.

Returning to your return value question:

sub ReturnAHash()
         {
         my %hHash =
                 (
                 string  => "hello",
                 number => 1,
                 );
         }

sub ReturnAnArray()
         {
         my @Array =
                 (
                 "foo",
                 "bar",
                 "baz",
                 );
         }

my %hReturnedHash = ReturnAHash();
my @aReturnedArray = ReturnAnArray();
print "$_ => $hReturnedHash{$_}\n" foreach sort(keys %hReturnedHash);
print "$_\n" foreach @aReturnedArray;

>'There's always more than one way to do it' can be very confusing at times..
>--
>Martijn van Exel, [EMAIL PROTECTED]
>
>WEBkitchen
>Waterstraat 11
>3511 BW Utrecht
>tel/fax 030-6701818
>
>http://www.webkitchen.nl

Aaron Craig
Programming
iSoftitler.com

Reply via email to