-1

Are the following two snippets functionally equivalent? When I do it the first way, I get a bunch of use of uninitialized value warnings because I try to evaluate the nonexistent $seen{$key}. Hoping to avoid this. $seen{$key} is always either 1 or undefined, it never takes on any other value throughout the script.

if($seen{$key}=='1'){

    print "key already seen\n";

}else{

    print "key not seen\n";
    #do stuff with key
    $seen{$key}='1';

}

~~~~

if(!$seen{$key}){
   print "key not seen\n";
   #do stuff with key
   $seen{$key}='1';
}else{

   print "key already seen\n";
}
Sam Weisenthal
  • 2,791
  • 9
  • 28
  • 66

2 Answers2

2

You should read the documentation of "Truth and Falsehood".

Basically "0", an empty string "" or undef is false. If you try to use a undef value in numerical context you will receive an error "Use of uninitialized value $variable in numeric ..."

chansen
  • 2,446
  • 15
  • 20
0

consider this:

#at start of script ----------
use warnings;
use strict;
# ----------------------------

if(exists $seen{$key}){

    print "key already seen\n";

}else{

    print "key not seen\n";
    #do stuff with key
    $seen{$key}='1';

}

Besides the issue of 'what is truth' (a truly layered question, not suitable for SO) you seem to not know the 'exist' function ..

you can get some background in this Stack Ooverflow 'Question/Answer' that discusses whats-the-difference-between-exists-and-defined

Community
  • 1
  • 1
lexu
  • 8,766
  • 5
  • 45
  • 63
  • Thanks for your answer. My script runs on data that's highly heterogeneous, and therefore often a variable will be undefined for one instance and defined for the next. For example, to generate variables, it could split one line of a csv file that looks like `a,b,c,d,e` and the next looks like `,,,a,`. I do quite a bit of calculation/comparisons with these variables. Do I need to check whether a variable exists before everything I do to them? That would require many more lines of code...( but I also don't want my script to generate hundreds of warnings) – Sam Weisenthal May 09 '14 at 15:12
  • Since you're not accessing distinct variables with different names, but rather hash-table entries, you should be able to write a generic accessor function that does the checking, then call that. – lexu May 12 '14 at 08:39