http://qs1969.pair.com?node_id=51024

Ovid has asked for the wisdom of the Perl Monks concerning the following question:

Without naming names and starting another CB log/nolog war (just kidding), I noticed some well-respected monks asserting in the CB that most uses of ref were wrong. Essentially, ref if used for deep magic that is beyond the means of most monks (such as this blowhard, for example).

Recently, I found a need to create a query string based upon some data in a hash. I couldn't find a module that did this, so I wrote the following:

sub createQueryString { # This routine expects a hash as an argument and will return a val +id query string with # hash keys as the names and hash values as query string values. +If multiple values # are associated with one key, pass them as an array reference. my %data = ( @_ ); my ( $key, $value ); my $query_string = ''; # The following is a hexadecimal list of the characters that shoul +d be # uri encoded. This will be passed as the second argument to the # uri_escape() function. my $cgi_chars = '\x00-\x29\x2b\x2c\x2f\x3a-\x40\x5b-\x5e\x60\x7b- +\xff'; while (($key, $value) = each %data) { $key = uri_escape( $key, $cgi_chars ); if ( ref( $value ) eq "ARRAY" ) { # <- that' +s a ref! # We have multiple values for this key foreach ( @$value ) { my $array_value = uri_escape( $_, $cgi_chars ); $query_string .= "$key=$array_value&"; } } else { $value = uri_escape( $value, $cgi_chars ); $query_string .= "$key=$value&"; } } chop $query_string if $query_string; # remove trailing ampersand return $query_string; }
This code is very specific to my needs and does not guarantee to be appropriate for all uses. For example, whether or not a name is sent when there is no corresponding value depends upon the type of input field. Also, error checking is handled long before this routine gets the data, so this code is NOT robust. If you want it, use at your own risk.

So, putting those issues off to the side, is there something wrong with my use of ref here, or is there a better way to approach this?

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.