Make the "variants" an array and push items onto it. Then sift out unique values once all the data has been read.

use strict; use warnings; use Data::Dumper; open my $inFH, q{<}, \ <<EOD or die $!; The DT the International NN International for IN for well NN well preparation NN preparation preparation NN preparation in IN in conference NN conference conference NN conference conferences NN conference good VVG good EOD do { my $discard = <$inFH> }; my %hash; while ( <$inFH> ) { my @tags = split; next unless $tags[ 1 ] eq q{NN}; $hash{ $tags[ 2 ] }->{ frequency } ++; push @{ $hash{ $tags[ 2 ] }->{ variants } }, $tags[ 0 ]; } @{ $hash{ $_ }->{ variants } } = do { my %seen; grep { not $seen{ $_ } ++ } @{ $hash{ $_ }->{ variants } }; } for keys %hash; print Data::Dumper->Dumpxs( [ \ %hash ], [ qw{ *hash } ] );

The output.

%hash = ( 'preparation' => { 'frequency' => 2, 'variants' => [ 'preparation' ] }, 'conference' => { 'frequency' => 3, 'variants' => [ 'conference', 'conferences' ] }, 'well' => { 'frequency' => 1, 'variants' => [ 'well' ] }, 'International' => { 'variants' => [ 'International' ], 'frequency' => 1 } );

I hope this is helpful.

Update: Perhaps simpler would be to keep a ->{ seen }->{ $tags[ 0 ] } sub-sub-HoH to filter out duplicates and delete it at the end.

... while ( <$inFH> ) { my @tags = split; next unless $tags[ 1 ] eq q{NN}; $hash{ $tags[ 2 ] }->{ frequency } ++; push @{ $hash{ $tags[ 2 ] }->{ variants } }, $tags[ 0 ] unless $hash{ $tags[ 2 ] }->{ seen }->{ $tags[ 0 ] } ++; } delete $hash{ $_ }->{ seen } for keys %hash; ...

Cheers,

JohnGG


In reply to Re: multi dimensional hash by johngg
in thread multi dimensional hash by Anonymous Monk

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.