perl : question about defined()

Hi there

rather than doing this

if (defined($new)) {
    unless (defined($hostname)) {
        print "ERROR: If using --new, you must define a hostname\n";
        exit 1;
    }
}

is there some way of doing a "notdefined" (i appreciate there is no such thing :))

 if (defined($new) && notdefined($hostname)) {
        print "ERROR: If using --new, you must define a hostname\n"; 
        exit 1;
 }

any advise would be great

Hi,

If ( ! defined $var)  { print "test" ; }

Thanks pravin27, this works fine

        if (defined($new) && ( ! defined $hostname)) {
                        print "ERROR: If using --new, you must define a hostname\n";
                        exit 1;
        }

Actually, just playing around ...this seems to work

        if (defined($new) && (defined($hostname) eq "")) {
                        print "ERROR: If using --new, you must define a hostname\n";
                        exit 1;
        }

Hi,

You missed one closing bracket of IF .

 if (defined($new) && ( ! defined $hostname) ) {
                        print "ERROR: If using --new, you must define a hostname\n";
                        exit 1;
        }

While there is no such operator as notdefined, the Logical Not - not defined would work for your case. That's because not unary operator is the equivalent of the ! operator(except for the precedence).

$
$ perl -le '$new="x"; if(defined($new) && ! defined($hostname)){print "ERROR: If using --new, you must define a hostname"}'
ERROR: If using --new, you must define a hostname
$
$ perl -le '$new="x"; if(defined($new) && not defined($hostname)){print "ERROR: If using --new, you must define a hostname"}'
ERROR: If using --new, you must define a hostname
$

tyler_durden

thanks pravi27 (you were very quick, i realised i missed a bracket and edited the post pretty quickly) :slight_smile:

Tyler , thanks for the explanation, it is clear now :b: