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

Dear Monks, I created a hash array out of my first file (File 1) and wrote the cod +e like this:- File 1 looks like this:- John 10 Mathew 16 Andrew 27 #!/usr/bin/perl -w use strict; use warnings; my %href; my $fn = <>; open(FH, "$fn") || die "Cannot open file"; while (<FH>) { chomp($_); $href{$1} = $2 if $_ =~ /(\S+)\s+(\S+)/; } while (my ($key, $value) = each(%href)) { print $key. ", ". $value."\n"; } Okkkk. Now I have a 1.2 GB file thats I need to parse and print + my results based on my hash values and keys. File 2 Looks like this +:- File 2:- >John 40 34 40 40 40 40 17 40 40 35 40 40 40 40 40 40 40 20 40 40 40 30 40 4 +0 40 40 40 40 37 40 40 40 40 40 25 40 >Mathew 40 40 44 40 40 40 40 50 40 40 40 40 50 40 40 40 40 40 6 40 40 45 40 40 + 40 40 40 40 40 40 29 40 40 40 6 40 >Andrew 40 40 40 40 39 40 40 40 40 40 40 40 35 40 40 40 40 40 40 40 40 27 40 4 +0 40 40 40 40 33 40 40 40 40 4 40 40 ----------------------- END -------------------- Now what I need to do is suppose John in File 1 has value 10. So +in File 2 if only John record at the position 10 has the value >= 20 +I need to take it right and print it. Since John Record at 10th position = 35 which is greater than 20 so I +have to print my result as:- Result File:- John 10 35. Thanks

Replies are listed 'Best First'.
Re: Using hash to parse a Flat File
by kyle (Abbot) on Oct 20, 2008 at 17:05 UTC

    If your names always have a > before them, you could set $/ to that to pick out the records. It might look something like this:

    $/ = '>'; while ( <> ) { chomp; next if ! s{ \A (\S+) \s+ (?= \d ) }{}xms; my $name = $1; my @numbers = split /\D+/; my $one_number = $numbers[$href{$name} - 1]; if ( $one_number >= 20 ) { print "$name $href{$name} $one_number\n"; } }

    The above code is not tested, but it should be a good start.

    By the way, %href is not a very good name for a hash. It's only a little better if it's the name of a hash reference, or maybe if you're storing URLs.

    Also by the way, it's better to use <code> tags only for your code and not for the whole article.

Re: Using hash to parse a Flat File
by apl (Monsignor) on Oct 20, 2008 at 18:27 UTC
    You might want to modify the die in open(FH, "$fn") || die "Cannot open file"; to contain $fn and $! (the returned error-code). At some point, you'll be grateful.