Gavin has asked for the wisdom of the Perl Monks concerning the following question:

Would below code allow me to check the contents of the hash? follow on from delimited tab text file. while (<INFILE>){ chomp; next unless (/\t/); my ($key, $value ) = split(/\t/, $_, 2); $values{$key}=$value; foreach $key (keys %value) { print OUTPUT "$values {$key}\n"; } }

Replies are listed 'Best First'.
Re: Checking Hash contents
by kiyose (Scribe) on Mar 08, 2006 at 21:56 UTC
    There are some problems with the code here. First, you need to make sure that you are keeping the hash %values separate from the scalar $value. Secondly, I'd move the foreach outside the while or you will be getting quite a lot of repetitive output.
    Try this as a quick rewrite.
    my %values; while (<INFILE>){ chomp; next unless (/\t/); my ($key, $value ) = split(/\t/, $_, 2); $values{$key}=$value; } foreach my $key (sort keys %values) { print OUTPUT "$key: $values{$key}\n"; }
    If you'd rather just log it as the file is read you can get rid of the foreach and move the print statement back inside the while.
Re: Checking Hash contents
by runrig (Abbot) on Mar 08, 2006 at 21:54 UTC
    You have a space between "$values" and "{$key}" in your print statement that use strict would have caught. Once that is fixed, since the foreach...print loop is inside the while loop, you will be reprinting an ever increasing number of hash values for every value you read in. So move the foreach loop outside of the while loop. And this can not be a complete program, since you open neither INFILE nor OUTPUT...it would have been better if you posted a (small, but) complete example.

    Note: the OP is a duplicate of a node in this thread.

Re: Checking Hash contents
by GrandFather (Saint) on Mar 08, 2006 at 23:07 UTC

    Modules such as Data::Dump::Streamer are very useful in this sort of context for a diagnostic dump of the contents of a variable. Consider:

    use strict; use warnings; use Data::Dump::Streamer; my @strings = ("key1\tvalue1", "key2\tvalue2", "key3\tvalue3"); my %values = map {/([^\t]+)\t(.*)/; $1 => $2} @strings; Dump (\%values);

    Prints:

    $HASH1 = { key1 => 'value1', key2 => 'value2', key3 => 'value3' };

    DWIM is Perl's answer to Gödel