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

#!/usr/bin/perl use strict; use warnings; use strict 'vars'; use Getopt::Std; #Setting options # u:username # h:hostname # p:password # k:SSH Key getopts("u:h:p:k:"); package opts; our ($opt_u, $opt_h); #### TEST SECTION ### print $opts::opt_u;
$./ldapuser.pl -u hello Use of uninitialized value in print at ./ldapuser.pl line 25.
$./ldapuser.pl Use of uninitialized value in print at ./ldapuser.pl line 25.

????Any ideas??? I've tried print $opt_u; and my ($opt_u, $opt_h); print $opt_u; as well.

Replies are listed 'Best First'.
Re: Use of uninitialized value in print
by ikegami (Patriarch) on Mar 26, 2009 at 20:18 UTC
    getops was call from main::, so it populated $main::opt_u
Re: Use of uninitialized value in print
by kyle (Abbot) on Mar 26, 2009 at 20:20 UTC

    Here's one that works:

    #!/usr/bin/perl use strict; use warnings; use strict 'vars'; use Getopt::Std; #Setting options # u:username # h:hostname # p:password # k:SSH Key getopts("u:h:p:k:"); our ($opt_u, $opt_h); #### TEST SECTION ### print "opts::$opt_u\n";

    In your version, you refer to $opts::opt_u, which is a package variable in the "opts" package. strict won't complain about that because you've given the full name of the package variable, but that doesn't change the fact that there's nothing in it. Your call to getopt will set $main::opt_u instead (because that's what package it's called in).

Re: Use of uninitialized value in print
by toolic (Bishop) on Mar 26, 2009 at 20:37 UTC
Re: Use of uninitialized value in print
by mikelieman (Friar) on Mar 26, 2009 at 20:34 UTC
    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
      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";