Perl hash not initialising as expected -
i getting unexpected results perl hash (associative array).
i trying populate cgi post, form values might missing.
use strict; use data::dumper; use cgi; $cgi = new cgi; %data = ( 'key1' => $cgi->param('fkey1'), 'key2' => $cgi->param('fkey2'), 'key3' => $cgi->param('fkey3'), 'key4' => $cgi->param('fkey4'), 'key5' => $cgi->param('fkey5'), 'key6' => $cgi->param('fkey6'), 'key7' => $cgi->param('fkey7'), 'key8' => $cgi->param('fkey8'), 'key9' => $cgi->param('fkey9'), 'key0' => $cgi->param('fkey0'), ); print "content-type: text/html\n\n<pre>"; print dumper \%data; $fkey1 = $cgi->param('fkey1'); $fkey2 = $cgi->param('fkey2'); $fkey3 = $cgi->param('fkey3'); $fkey4 = $cgi->param('fkey4'); $fkey5 = $cgi->param('fkey5'); $fkey6 = $cgi->param('fkey6'); $fkey7 = $cgi->param('fkey7'); $fkey8 = $cgi->param('fkey8'); $fkey9 = $cgi->param('fkey9'); $fkey0 = $cgi->param('fkey0'); %data2 = ( 'key1' => $fkey1, 'key2' => $fkey2, 'key3' => $fkey3, 'key4' => $fkey4, 'key5' => $fkey5, 'key6' => $fkey6, 'key7' => $fkey7, 'key8' => $fkey8, 'key9' => $fkey9, 'key0' => $fkey0, ); print "content-type: text/html\n\n<pre>"; print dumper \%data2;
%data wrong. have %data2. output of is:
$var1 = { 'key9' => 'key0', 'key5' => 'key6', 'key1' => 'key2', 'key7' => 'key8', 'key3' => 'key4' }; $var1 = { 'key9' => undef, 'key5' => undef, 'key6' => undef, 'key8' => undef, 'key0' => undef, 'key3' => undef, 'key2' => undef, 'key1' => undef, 'key4' => undef, 'key7' => undef };
so if $cgi->param('fkey1') undef, skips value , uses next key value. there need %data working?
this problem due way param
behaves in list context vs. scalar context.
in scalar context, if parameter doesn't exist, param
returns undef
. in list context, returns empty list. suppose have hash initialization this:
my %data = ( foo => $cgi->param( 'foo' ), bar => $cgi->param( 'bar' ), baz => $cgi->param( 'baz' ) );
and suppose parameter bar
not exist. since param
called in list context, list passed hash initialization ends looking this:
( 'foo', 'foovalue', 'bar', 'baz', 'bazvalue' )
note there's nothing after bar
key, because empty list returned there.
to fix it, can force calls param
scalar context:
my %data = ( foo => scalar $cgi->param( 'foo' ), bar => scalar $cgi->param( 'bar' ), baz => scalar $cgi->param( 'baz' ) );
now list this:
( 'foo', 'foovalue', 'bar', undef, 'baz', 'bazvalue' )
and right world again.
Comments
Post a Comment