Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: preserving hash value outside the loop

by hippo (Bishop)
on May 11, 2016 at 09:48 UTC ( [id://1162727]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1162727]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (1)
As of 2024-04-25 19:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found