On 1/11/19 11:16 AM, Bruce Gray wrote:


On Jan 11, 2019, at 12:41 PM, ToddAndMargo via perl6-users 
<perl6-us...@perl.org> wrote:

Hi All,

How do I do a hash inside a hash?

So far I have:

$ p6 'my %Vendors=("acme" => ( "ContactName" => "Larry, "AccountNo" => 1234 ) 
); say %Vendors;'
===SORRY!=== Error while compiling -e


I want to be able to have both a Contact Name and and AccountNo
associated with each key in %Vendors.


Many thanks,
-T

First, you need a double-quote after `Larry` (before the comma) to fix the 
syntax error:
        perl6 -e 'my %Vendors=("acme" => ( "ContactName" => "Larry", "AccountNo" 
=> 1234 ) ); say %Vendors;'

At this point, you have a Hash of List of Pairs. To change it into a Hash of 
Hashes, change the inner parens to curly braces:
        perl6 -e 'my %Vendors=("acme" => { "ContactName" => "Larry", "AccountNo" => 1234 } 
); say %Vendors; say %Vendors<acme><AccountNo>;'

Those inner parens were acting as an anonymous list constructor, but you needed 
an anonymous *hash* constructor, which is what the curly braces do (when they 
are not doing their code-block-ish job).

You could have also used `Hash(…)` or `%(…)` instead of `{…}`, but `{…} is 
shortest, and most traditional from Perl 5.

—
Hope this helps,
Bruce Gray (Util of PerlMonks)


Hi Bruce,

Thank you!

This works,

$ p6 'my $x="Ace"; my %Vendors=("acme" => { "ContactName" => "Larry", "AccountNo" => 1234 }, "Ace" => { "ContactName" => "Mo", "AccountNo" => "A102" } ); say "%Vendors<Ace><ContactName>" ~ "\t" ~ "%Vendors<Ace><AccountNo>";'
Mo      A102


but I have to access it by a variable.  "Now" what am I doing wrong?

$ p6 'my $x="Ace"; my %Vendors=("acme" => { "ContactName" => "Larry", "AccountNo" => 1234 }, "Ace" => { "ContactName" => "Mo", "AccountNo" => "A102" } ); say "%Vendors<$Ace><ContactName>" ~ "\t" ~ "%Vendors<$Ace><AccountNo>";'
Use of uninitialized value of type Any in string context.


Many thanks,
-T

Reply via email to