Hi All,

I have two files to compare. Each has 10 columns with first 4 columns being key index together. The rest of the columns have monetary values.

I want to read one file into hash; check for the key value availability in file 2; then compare the values in the rest of 6 columns; report the differences found.

The files are comman separated and do not have header

Here is the sample file:
File A:
Row1: abcd,abrd,fun,D000,$15,$236,$217,$200,$200,$200
Row2: dear,dare,tun,D000,$12.00405,$234.08976,$212.09876,$200,$200,$200

File B:
Row1: abcd,abrd,fun,D000,$12,$234,$212,$200,$200,$200
Row2: dear,dare,tun,D000,$12.00405,$234.08976,$212.09876,$200,$200,$200

Difference found for index abcd,abrd,fun,D000 for field 5,6 and 7

Any help would be appreciated. I am able to come up with the script in Bash, but not very comfortable with the concept of Hash in Perl and also setting up key index columns.


8 Years
Discussion Span
Last Post by Perlhelp

I'm not comfortable with setting up key index columns but I may be able to answer some questions about a hash. With what about the concept of hash are you not comfortable?

The main things you need to know, in order to read a file into a hash are

  • How to declare a hash
  • How to add a key-value pair to a hash and that only scalar keys and values can be stored in a hash
  • How to check if a particular key exists in your hash, and if it does, how to access it
  • How to iterate through your keys so you can access all the key-value pairs

Given a file named b.txt which contains the following:


here is an example of how you can read this file into a hash and then iterate through and print the keys and values:

#!/usr/bin/perl -w
use strict;
use warnings;
my $filename_b = '/home/david/Programming/Perl/b.txt';
my %b = %{read_into_hash($filename_b)};

foreach (keys %b) {
    print "The key $_ has $b{$_} as its value\n";
    my $aref = $b{$_};
    print "$b{$_} is a reference to an array containing @{$aref}\n";

sub read_into_hash {
    my $file = $_[0];
    my %h = ();
    open (my $fh, '<', $file);
    while (<$fh>) {
        my @fields = split(/,/);
        my $hkey = join(",", @fields[0..3]);
        $h{$hkey} = [@fields[4..9]];
    return \%h;

Edited by d5e5: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.