siery siery - 7 months ago 108
Perl Question

Use of uninitialized values in an list

I load some variables from HTML and want to check in my CGI script if they are initialized. Quickly I find out, I can not put uninitialized values to an list in Perl. My approach was simply to iterate trough the list and use a switch (1 if all data been initialized 0 elsewhere).

I come up with this:

### Read data from HTML
my $mailinglist = param('mailinglist');
my $firstname = param('firstname');
my $lastname = param('lastname');
my $mail = param('mail');

my $sucessDOM = 0;

my @DOM = { $mailinglist, $firstname, $lastname, $mail };

### Data validation
for my $data (@DOM) {
if ($data eq undef) {
$sucessDOM = $sucessDOM + 1;
}
if ($sucessDOM = @DOM) {
print "@DOM\n";
$sucessDOM = 1;
} else {
$sucessDOM = 0;
}
}


The output is fallowing:

[Fri Dec 22 20:30:40 2017] read_form.cgi: Use of uninitialized value $mailinglist in anonymous hash ({}) at ./read_form.cgi line 20.
[Fri Dec 22 20:30:40 2017] read_form.cgi: Use of uninitialized value $lastname in anonymous hash ({}) at ./read_form.cgi line 20.
[Fri Dec 22 20:30:40 2017] read_form.cgi: Use of uninitialized value in string eq at ./read_form.cgi line 24.
HASH(0x55c8a73eeea8)


I can not also get why are there only errors for two values in the array if are all uninitialized as I run script directly with no values passing.

Answer Source

You have at least four problems with your code:

First, {} makes an anonymous hash and returns a reference to it; this is a single value that ends up in @DOM. The warnings are because hash keys have to be strings, and warn if they are undef. You should be assigning like

my @DOM = ( $mailinglist, $firstname, $lastname, $mail );

Second, eq compares strings, so it would convert undef to ''. To test if $data is undef, do

if (! defined $data) {

Third, you are checking if all the array elements were successful inside the for loop (where that will not be true on any but the last iteration of the loop). Move the if ($successDOM... block to after the for loop.

Fourth, = is just an assignment operator; use == for numeric comparison:

if ($successDom == @DOM) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download