develooper Front page | perl.beginners | Postings from January 2002

Re: What's wrong with this?

Thread Previous | Thread Next
Curtis Poe
January 31, 2002 08:30
Re: What's wrong with this?
Message ID:

--- Jan Gruber <> wrote:
> Hi !
> Sorry for the previous posting, im not yet completely awake ;o) 
> > > >How can the param's be placed into a new hash?
> > >
> > > has a Vars() method, I believe, which returns a hash.
> > >
> > >   use CGI;
> > >   my $q = CGI->new;
> > >   $data = $q->Vars;
> > >
> > >   print $data->{field};  # etc.
> Just a little add on:
> I had to use  CGI ':cgi-lib'; to get the $q->Vars function working.
> I think %data = $q->vars would be better to read and I'm not sure if the 
> Vars() function returns a reference or a hash.

It returns either a hash or a hash reference, depending upon the context in which it was called:

    my $data = $q->Vars; # returns a hash ref

    my %data = $q->Vars; # returns a hash

However, I never use CGI::Vars().  The reason that I do not use it is due to how it returns the
data.  Check out this example:

C:\>perl -MCGI=:standard,:cgi-lib -e "use Data::Dumper; print Dumper {Vars}" color=red color=blue
$VAR1 = {
          'color' => 'red blue'

As you can see, the value of 'color' is a scalar, not an array reference.  The individual elements
on separated by NULs (ASCII zero).  This can cause several problems.

1.  It's not intuitive to a new programmer what's going on.
2.  Due to the poison NUL byte hack, it's best not to introduce them.
3.  Why not just return a proper data structure?

As for item 3, I realize that Lincoln Stein did this to ease the migration difficulties of those
using the Perl4  However, I can think of no other legitimate use.  Here's a nice,
clean method of dealing with this:

    use strict;
    use CGI qw/:standard/;
    my %form_data = map { $_, get_data($_) } param;

    sub get_data 
        my $name   = shift;
        my @values = param( $name );
        return @values > 1
            ? \@values
            : $values[0];

In this case, if you only have one value for a parameter, you will have a direct mapping of key to
a scalar value.  If you have more than one value, you will have a mapping of a key to an array



    $VAR1 = {
              'color' => ['red', 'blue'],
              'name' => 'Ovid'

Curtis "Ovid" Poe

"Ovid" on
Someone asked me how to count to 10 in Perl:
push@A,$_ for reverse q.e...q.n.;for(@A){$_=unpack(q|c|,$_);@a=split//;
shift@a;shift@a if $a[$[]eq$[;$_=join q||,@a};print $_,$/for reverse @A

Do You Yahoo!?
Great stuff seeking new owners in Yahoo! Auctions!

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About