develooper Front page | perl.perl6.users | Postings from January 2019

Re: I need hash inside a hash help

Thread Previous | Thread Next
From:
Bruce Gray
Date:
January 11, 2019 19:16
Subject:
Re: I need hash inside a hash help
Message ID:
DF266AFB-E59B-4E9A-9107-B2B0FA0F2F73@acm.org


> On Jan 11, 2019, at 12:41 PM, ToddAndMargo via perl6-users <perl6-users@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)

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About