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

I have written a script to grap the duplicate row of a file.
1 #!/usr/bin/perl -w 2 use strict; 3 my %dup; 4 while(<>){ 5 my @row=split(/\s+/,$_); 6 $dup{$row[3]}=$dup{$row[3]}+1; #if change to $dup{$row[3]}++, it w +ill run smoothly no error report 7 } 8 9 foreach my $id (keys %dup){ 10 if ($dup{$id}>1) { 11 print "$id\t$dup{$id}\n"; 12 } 13 }
it report the error: "Use of uninitialized value in addition (+) at dup.pl line 6.." If I change that line code to "$dup{$row3}++", then it's all right. Who can tell me why this happened? Thanks.

Replies are listed 'Best First'.
Re: why such an error?
by FunkyMonk (Bishop) on Sep 25, 2008 at 19:07 UTC
    ++ is magic in this regard. See Auto increment and decrement in perlop:
    undef is always treated as numeric, and in particular is changed to 0 before incrementing (so that a post-increment of an undef value will return 0 rather than undef).
      Thank you for your answer. Other than using the magic "++". Could we have another method to define the $dup{$row[3]}? Thanks.

        There are a number of ways you could do it:

        $dup{$row[3]} = $dup{$row[3]} + 1; # Has trouble with undef $dup{$row[3]} += 1; ++$dup{$row[3]}; $dup{$row[3]}++;

        += and ++ are magical to the extent that they can update an undef value without complaint. That is often very useful, especially where a hash or array element is autovivified. For example, if you are using a hash to count the number of occurrences of words in a string you could:

        ++$wordCount{$_} for split ' ', $string;

        which generates an entry in %wordHash for each word and increments the count - very clear and concise.


        Perl reduces RSI - it saves typing

        You seem to have an inclination for dyadic plus ;-)

        $dup{$row[3]} = ($dup{$row[3]}||0) + 1;

        -- 
        Ronald Fischer <ynnor@mm.st>