> $hash{(split)[0]}{(split)[1]} = 1 foreach <>;

> How can I achieve a similar result using map?

not "really", to do so you would need to use map in void context in order to act like foreach!

DB<163> map { ($a,$b)=split /\s+/; $hash{$a}{$b}=1 } <I>; => (1, 1, 1, 1) DB<164> \%hash => { Canberra => { 12 => 1, 18 => 1 }, Sydney => { 12 => 1, 14 => 1 } + }

(Please note that you are calling split twice, I avoided this by setting $a and $b and have full control over the delimiter.)

You can't have map returning nested hashes assigned to a top-level hash, otherwise entries from different lines would collide (2 x Sidney, 2 x Canberra) and be overwritten:

 %hash = map { entry1 => { entry2 => 1} } <> # collisions of entry1

Another concise way to do it, involving a "real" map and avoiding named variables:

DB<143> $hash{$_->[0]}{$_->[1]} = 1 for map { [split /\s+/] } <I> => "" DB<144> \%hash => { Canberra => { 12 => 1, 18 => 1 }, Sydney => { 12 => 1, 14 => 1 } + }

Of course creating an anonymous array is not optimal...

Cheers Rolf

( addicted to the Perl Programming Language)


In reply to Re: Possible for Map to create Hash of Hash? by LanX
in thread Possible for Map to create Hash of Hash? by konnjuta

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.