in reply to Re: preserving hash value outside the loop
in thread preserving hash value outside the loop

yes I declared $key outside the loop but then this is also the problem that it gives the last value set to $key. Actually I want to print each value of $key and $key1 separated by tab.
  • Comment on Re^2: preserving hash value outside the loop

Replies are listed 'Best First'.
Re^3: preserving hash value outside the loop
by hippo (Archbishop) on May 11, 2016 at 10:59 UTC

    So, why not prepend the key to the list in the first loop instead:

    #!/usr/bin/env perl use strict; use warnings; my %seen; $/ = ""; while (<>) { chomp; my ($key, $value) = split ('\t', $_); my @lines = split /\n/, $key; my $key1 = $lines[1]; $seen{$key1} //= [ $key ]; push (@{$seen{$key1}}, $value); } foreach my $key1 (sort keys %seen) { print join ("\t", @{$seen{$key1}}); }

    If this doesn't do it for you then perhaps you might state what grander problem it is that you are trying to solve and a better overall approach might be in order.