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

Hi, I would like to compare tow hashes which as "filename" as "key" and "filesize" as "values" first i have to check for identical filename in the two hashes and then compare the both hasses filesize as well if both are identical then leave it or else the filename should be copied to an array. thanks in advance

Replies are listed 'Best First'.
Re: hash compare
by LanX (Saint) on Apr 10, 2013 at 14:45 UTC
    Quite straightforward when you look at while and each.

    Then plz show your efforts in using them.

    Cheers Rolf

    ( addicted to the Perl Programming Language)

Re: hash compare
by SuicideJunkie (Vicar) on Apr 10, 2013 at 14:50 UTC

    Comparison of strings such as filenames should use the cmp operator which will return -1, 0 or +1 to show which value comes first.
    Comparison of numerical values should use <=> which will also return -1, 0 or +1 to show which value is bigger.

    Zero meaning the two values are equal, of course

Re: hash compare
by stevieb (Canon) on Apr 10, 2013 at 14:53 UTC

    It would have been nice if you showed what you tried, but here's a pretty simplistic way to do what you want:

    #!/usr/bin/perl use warnings; use strict; use 5.12.0; my %h1 = ( a => 1, b => 2, c => 3, e => 5, ); my %h2 = ( a => 2, b => 2, d => 4, e => 5, ); my @filenames; while ( my ( $k, $v ) = each %h1 ) { if ( exists $h2{ $k } ) { push @filenames, $k if $v == $h2{ $k }; } } say "$_" for @filenames;

    Steve

Re: hash compare
by choroba (Cardinal) on Apr 10, 2013 at 15:09 UTC
    You did not specify what to do if the file is missing in one of the hashes. The following code informs you about all the possible situations:
    #!/usr/bin/perl use warnings; use strict; use feature qw(say); my %size1 = ( 'autorun.inf' => 42, 'autoexec.bat' => 118, 'eicar.zip' => 186, ); my %size2 = ( 'autorun.inf' => 42, 'autoexec.bat' => 119, 'ibmbio.com' => 234186, ); my %files; undef @files{keys %size1, keys %size2}; for my $file (keys %files) { delete $files{$file}, next if exists $size1{$file} and exists $size2{$file} and $size1{$file} == $size2{$file}; $files{$file} = 'Missing in 1', next unless exists $size1{$file}; $files{$file} = 'Missing in 2', next unless exists $size2{$file}; $files{$file} = 'Size changed'; } for my $file (keys %files) { say "$file\t$files{$file}"; }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: hash compare
by tobyink (Canon) on Apr 11, 2013 at 07:00 UTC

    Test::Deep::NoTest is a good tool for comparing data structures.

    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name