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

I have a database setup to create a webmenu

Each menu can have up to 15 links

I Execute a select * from table and assign it to array

Running debug the follwing Menus are created, I want to use is a while statement that breaks when it hits a variable that is undefined or null in the database.

$VAR1 = "AirDefense"; $VAR2 = 2; $VAR1 = "Mobile-N-Site"; $VAR2 = 4; $VAR1 = "Owl"; $VAR2 = 6; $VAR1 = undef; $VAR2 = 8;

using the results above

I defined a variable my $undef = 'undef';

Created a while loop to loop through until undef was found

when i run the loop it never breaks out until it hits all 15 items in the database

while (@MyData[[$y]] ne $undef)

Thanks for the help, Michael

Replies are listed 'Best First'.
Re: Breaking out of undef/null database reads
by stevieb (Canon) on Aug 05, 2016 at 16:50 UTC

    undef is a state, not a string. Change 'undef' to undef.

    ne is a string operator. You can use either == to check if the value is false (which undef is), or better yet, use the defined() function within a for() loop.

    This will skip each undefined element, and continue:

    for (@MyData){ next if ! defined; ... }

    This will break out of the loop entirely when it hits the first undef:

    for (@MyData){ last if ! defined; ... }
Re: Breaking out of undef/null database reads
by Marshall (Canon) on Aug 05, 2016 at 17:07 UTC
    It is really hard to understand what you are doing without the actual code in <code>..</code> tags. How you are accessing the DB? Your while loop as shown does nothing useful. Do you have any output at all to show?

    Update: Another thought if you show your SQL statement, there may be a way so that these 'undef' columns do not even show up from the DB. I think stevieb is right that a "real" undefined value shows up instead of the string 'undef' although that may not be apparent from whatever printout you are looking at.

    Just a guess at something that you might be trying to do, form a menu from an row from the DB...

    #!usr/bin/perl use warnings; use strict; use Data::Dumper; use List::Pairwise qw(mapp grepp); ##need to install this module my @ary = qw(AirDefense 2 Mobile-N-Site 4 Owl 6 undef 8); my %hash = mapp{$a ne 'undef' ? ($b,$a):()}@ary; foreach my $opt (sort{$a<=>$b} keys %hash) { print "$opt => $hash{$opt}\n"; } __END__ 2 => AirDefense 4 => Mobile-N-Site 6 => Owl