Pam Derks wrote:
> 
> Hi all,

Hello,

> I have 2 files that contain a filename and # of hits
> I've split the contents of these 2 files into %hash1 and %hash2
> I want to find out the difference in the # of hits
> can someone shed some light on the approach I should take.
> 
> I've gotten this far:
> 
> sample data:
> FILE1
> arts.html 95
> arttherapy.html 102
> award.html 277
> bayart.html 1
> best.html 1
> 
> FILE2
> arts.html 101
> arttherapy.html 103
> award.html 282
> bayart.html 2
> best.html 2
> splat.html 10  (note this is not in FILE1)
> 
> DESIRED OUTPUT:
> arts.html 6
> arttherapy.html 1
> award.html 10
> best.html 1
> splat.html 10
> 
> #!/usr/bin/perl -w

use strict;

> $dir = "/dept/unxmkt/bin/hits/news/by_month";

my $dir = '/dept/unxmkt/bin/hits/news/by_month';


> chomp(@ARGV);

This serves no useful purpose (try entering a command line option with a
newline on the end.)


> $file1 = shift(@ARGV);
> $file2 = shift(@ARGV);

my $file1 = shift;
my $file2 = shift;


> print("$file1 $file2\n");
> 
> open(FILE1, "$dir/$file1.total") or die ("nope: $!");
> open(FILE2, "$dir/$file2.total") or die ("nope: $!");
> 
> while(<FILE1>){
>         my(%hash1, $key1, $value1);

You are declaring %hash1 as local to the while loop so it can't be used
outside of this loop.

>         ($key1, $value1) = chomp && split;
                             ^^^^^^^^
The chomp() is unnecessary as split() removes ALL whitespace characters
(including \r and \n.)


>         $hash1{$key1} = $value1;
> 
>         for (keys %hash1){

%hash1 always has one key as it is created each time the loop starts.

>                 print("$hash1{$key1}\n");
>         }
> 
> }
> 
> print("------------------------------\n");
> 
> [snip]

This should do what you want:

#!/usr/bin/perl -w
use strict;

my $file1 = shift;
my $file2 = shift;

print "$file1 $file2\n";
print '-' x 30, "\n";

my %hash;

open FILE, $file1 or die "nope: $!";
while ( <FILE> ) {
    my ( $key, $value ) = split;
    $hash{ $key } = $value;
    }
close FILE;

open FILE, $file2 or die "nope: $!";
while ( <FILE> ) {
    my ( $key, $value ) = split;
    if ( exists $hash{ $key } ) {
        # key exists in file1 so calculate difference
        $hash{ $key } = $value - $hash{ $key };
        }
    else {
        # key is only in file2
        $hash{ $key } = $value;
        }
    }
close FILE;

# print out the results (sorted)
for my $key ( sort keys %hash ) {
    print "$key $hash{$key}\n";
    }

__END__



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to