Why does Perl complain about “Using uninitialized value” in my CGI script?

I clean my Perl code for product release and came across a weird warning in the Apache error log.

It says:

[Thu Nov 5 15:19:02 2009] Clouds.pm: Use of uninitialized value $name in substitution (s///) at /home/mike/workspace/olefa/mod-bin/OSA/Clouds.pm line 404.

The relevant code is here:

my $name         = shift @_;
my $name_options = shift @_;

$name_options = $name_options eq 'unique'     ? 'u'
              : $name_options eq 'overwrite'  ? 'o'
              : $name_options eq 'enumerate'  ? 'e'
              : $name_options =~ m/^(?:u|o|e)$/ ? $name_options
              : q();

if ($name_options ne 'e') {
   $name =~ s/ /_/g;
}

So, why the warning about an uninitialized variable since it is explicitly initialized?

+3
source share
3 answers

A warning simply means that it was $namenever filled with a value, and you tried to perform a replace ( s///) operation on it. The default value of the variable is undefined ( undef).

script, $name @_. , @_ , undef.

+12

, , . , - $name, croak, -. , .

, , -, $name_option. $name_option undefined:

use 5.010;

use Carp;

BEGIN {
my %valid_name_options = map {
    $_
    substr( $_, 0, 1 ),
    } qw( unique overwrite enumerate );

some_sub {
    my( $name, $name_options ) = @_;

    croak( "Name is not defined!" ) unless defined $name;
    $name_options = $valid_name_options{$name_options} // '';

    if ($name_options ne 'e') {
        $name =~ s/ /_/g;
        }

    ...
    }
}
+3

, , " ". ( : CGI ).

,

print "testing: ", defined($name)? "defined: '$name'" : "undef", "\n";

. :

  • "testing: undef" --- , undefined. , . caller(), , , .
  • ! , . ( , , ).
  • ": defined:" some data "--- ---. ask a question about stackoverflow.
+1
source

Source: https://habr.com/ru/post/1721994/