in reply to preserving hash value outside the loop

Yes, it is possible. Simply declare $key outside the while loop instead of inside it. See Coping with Scoping.

Of course you'll only see the value from the last time $key is set but it's not immediately clear from your post if that's a problem for you.

Replies are listed 'Best First'.
Re^2: preserving hash value outside the loop
by Anonymous Monk on May 11, 2016 at 10:31 UTC
    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.

      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.