On 6/27/07, perl_power <[EMAIL PROTECTED]> wrote:
Tom,

I did make some changes but that actually is still causing me to
output each line while looping through the file instead of only adding
unique key value pairs to the hash.  I can only guess I am overriding
the hash each time it loops?  Also don't understand the line break I
am getting between the number and is unique.
snip

Here is the output I get from your code:
The cellphone is unique
The cola is unique
The monitors is unique
The mugs is unique

Okay, I see 3 possibilities.
   1. You are not running the code you think your are running
(unsaved file, saved to wrong file, etc)
   2. There is something weird about your environment you haven't told us yet.
   3. You copied the code by hand and fixed the bug in the transfer.

Also, here is a list of things you can do (or not do) to make your code better.
   1. always use the strict pragma
   2. always use the three argument version of open
   3. use \n inside strings rather than counting on a literal linefeed working
   4. numbering your errors in die is worthless, the file and line
number are printed automatically if the the error string does not end
with \n
   5. only use parenthesis when you really need them, "my (%hash);" is foolish
   6. learn when you need to specify the default variable ($_) and
when you don't
   7. never use an if statement just to get the else clause, use
"unless (exists $hash{$product})", "if (not exists $hash{$product})",
or "if (!exists $hash{$product})"

Here is your code after following the advice above.

#!/usr/bin/perl

use strict;
use warnings;

my $infile = 'products.out';
open my $file, '<', $infile
       or die "could not open $infile for reading:$!\nStopped";

my %hash;
while(<$file>) {
       my ($product, $qty) = split /\|/;
       unless (exists $hash{$product}) {
               $hash{$product} = $qty;
               print "The $product is unique\n";
       }
}

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to