CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Intermediate: Re: [abhi] compare files: Edit Log


Feb 26, 2013, 11:37 AM

Views: 1940
Re: [abhi] compare files

Building upon the wisdom of BillKSmith and Laurent_R, consider the following which uses File::Slurp (only to easily handle the file i/o) and Test::More (to do a 'deep' comparison of the two hash structures built from the two files):

use strict; 
use warnings;
use File::Slurp qw/read_file/;
use Test::More tests => 1;

my ( %file1, %file2 );

do { chomp; $file1{$_}++ } for read_file 'file1.txt';
do { chomp; $file2{$_}++ } for read_file 'file2.txt';

is_deeply( \%file1, \%file2 );

Output if same:

ok 1

Output if different:

not ok 1
# Failed test at ... line 11.
# Structures begin differing at:
# $got->{123} = '1'
# $expected->{123} = Does not exist
# Looks like you failed 1 test of 1.

Why use a hash? In this case, the hashes track the number of times the content of lines (as keys) appears. For example, if "abc" occurs in file1.txt only once, then the value of $file1{abc} will be 1, and the value will be 2 if "abc" occurs twice...

(This post was edited by Kenosis on Feb 26, 2013, 11:39 AM)

Edit Log:
Post edited by Kenosis (User) on Feb 26, 2013, 11:39 AM

Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives