in reply to Use of uninitialized value in print

This demonstrates the use of the conditional and print to handle the undefined value without warning.
#!/usr/bin/perl use strict; use warnings; use strict 'vars'; use Getopt::Std; #Setting options # u:username # h:hostname # p:password # k:SSH Key our ($opt_u, $opt_h, $opt_p, $opt_k); getopts("u:h:p:k:"); #### TEST SECTION ### print "\$opt_u="; print $opt_u ? $opt_u : "Undefined" ; print "\n"; print "\$opt_h="; print $opt_h ? $opt_h : "Undefined" ; print "\n"; print "\$opt_p="; print $opt_p ? $opt_p : "Undefined" ; print "\n"; print "\$opt_k="; print $opt_k ? $opt_k : "Undefined" ; print "\n"; $ ./test.pl $opt_u=Undefined $opt_h=Undefined $opt_p=Undefined $opt_k=Undefined $ ./test.pl -u abc -h def -p ghi -k jkl + $opt_u=abc $opt_h=def $opt_p=ghi $opt_k=jkl

Replies are listed 'Best First'.
Re^2: Use of uninitialized value in print
by toolic (Bishop) on Mar 27, 2009 at 00:34 UTC
    I have gotten into the habit of checking options using defined just in case 0 is a legal value. The code you show treats 0 as an undefined value.
    $ ./test.pl -u 0 $opt_u=Undefined $opt_h=Undefined $opt_p=Undefined $opt_k=Undefined

    I realize that in this particular application, 0 is unlikely to be a username, password, etc., but it does not hurt to account for this corner case:

    print "\$opt_u="; print defined $opt_u ? $opt_u : "Undefined" ; print "\n";