Just to give a little more insight to this problem, when you assign a hash, you're essentially assigning a list (which is why things like my %args = @_; work), except by convention we use the "fat comma" operator ( => ) to denote key-value pairs. And a good convention it is - it is a synonym for the comma operator, but it forces any word to its left to be interpreted as a string (quoting perldoc perlop). That lets us drop the quotes around the left hand operand. In your example, this would be perfectly legal:
my %test_subscriptions = ( case_001 => # etc... );
As already mentioned, you'd like to create a hash of hashes, so you need the right hand operand of your initial fat comma to be a hash ref, which is constructed via curly brackets ( { } ).
Even then, you could use commas or fat commas interchangably, so either of these are valid, but just not customary ;)
my %hash = ( 'key1', 'value1', 'key2', 'value2' ); # or... my %hash = ( key1 => 'value1' => key2 => 'value2' );
Because you were using parens for your 'sub-hash', all you were really doing was creating a list, so perl interpreted what you were trying to do as:
my %test_subscriptions = ( 'case_001', 'fname' , "$lname", 'lname', "$fname", 'zip', '02486', 'email', 'test-' . $email . '\@mydomain.com', 'lists', ['news','updates'], # whoops, there's just a 'key' here of # an arrayref! - no associated value! );
So rightly so, perl complains about an odd number of elements, since it flattened your list without questioning anything, and because of the list flattening, you don't have a full set of key-value pairs. Running it through B::Deparse helps confirms this (though it doesn't show the extra list flattened):
$ perl -MO=Deparse hesco.pl my(%test_subscriptions) = ('case_001', ('fname', "$lname", 'lname', "$fname", 'zip', '02486', 'email', 'test-' . $email . '\\@mydomain.c +om', 'lists', ['news', 'updates']));
Change the % to an @ in your original code, and no complaints:
my @test_subscriptions = ( 'case_001' => ( 'fname' => "$lname", 'lname' => "$fname", 'zip' => '02486', 'email' => 'test-' . $email . '\@mydomain.com', 'lists' => ['news','updates'], ), ); print join( "\n", @test_subscriptions ), "\n"; #OUTPUT: $ perl hesco.pl case_001 fname lname zip 02486 email test-\@mydomain.com lists ARRAY(0x1801180)
Hope this helps explain the error you see a bit better!
s**lil*; $*=join'',sort split q**; s;.*;grr; &&s+(.(.)).+$2$1+; $; = qq-$_-;s,.*,ahc,;$,.=chop for split q,,,reverse;print for($,,$;,$*,$/)
In reply to Re: What's Odd about the number of elements in this hash assignment?
by chargrill
in thread What's Odd about the number of elements in this hash assignment?
by hesco
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |