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

How do I display only the fields that have been filled and not the ones that are empty? (These fields are not required.) For eg: If I have three fields Tier1, Tier2 and Tier3 and the user leaves the Tier3 field empty...I would like only the results of Tier1 and Tier2 to be displayed....

Tier1: Microbiology
Tier2: Chemistry

Replies are listed 'Best First'.
Re: Empty Fields
by Elliott (Pilgrim) on Oct 31, 2001 at 04:14 UTC
    Pretty tricky to answer without more background and/or code examples. On the surface
    if ($tier1) {print $tier1}
    seems to be what you're looking for. But there must be something else behind your question...?

      Or,

      print $tier1 if $tier1 ne "";
      which will print non-empty (rather than non-true, ie non-zero) fields

      --
      Tommy
      Too stupid to live.
      Too stubborn to die.

      Well, I am receiving a generated email with all the form field names and their associated values but this also includes fields w/o values....I am including the entire script that processes this form and generates an email with the form results....
      #!/usr/bin/perl #USAGE: #Hidden Field:::Value:::Action #validate:::fields for validation:::check for blank entries #email_field:::INPUT name of email field:::validate correct email form +at #subject:::[string]:::SUBJECT for email sent out #error_head:::[string]error_head.html:::header for error page rel. to +CGI location #error_foot:::[string]error_foot.html:::footer for error page rel. to +CGI location #recipient(s):::[e-mail addresses]:::the recipients of the e-mail #formname:::[string]:::name of form for datafile #VERSION HISTORY: #3.1 - Adjusted Documentation and Variable Values for Digex Env. #3.1 - fixed textarea whitespace problems #3.0 - Added datafile output # - Added datestamp to both email and datafile # - Added more robust error handling #2.2 - Added config variable for $mailapp (ie. sendmail path) # - Added config variable for $def_from (email from field) # - Fixed checkbox concat. so "" is chopped off beginnning #2.1 - Ordered the email's output same as forms input # - Changed the data parser for GET or POST and protected variables # - Fixed to allow for spaces in INPUT NAME(s) # - Changed the names of the hidden fields such as CheckExistence - +-> validate #2.0 - Added error_head and error_foot functionality for custom error +pages # - Fixed variable problems and logic cases not handled #USER CONFIGURATION: # The script admin var is email for receiving error messages. $script_admin = "ds\@blah.com"; $mailapp = "/usr/lib/sendmail -t"; $def_from = "mailform\@blah.com"; $datapath = "./data/"; # include trailing slash #change $dataurl if your datapath is url accessible #include trailing slash #$dataurl = "http://www.dynamind-llc.com/cgi-bin/data/"; #SYSTEM CONFIG DON'T EDIT! # set datestamp ($day, $month, $year) = (localtime)[3,4,5]; $year += 1900; $month += 1; $datestamp = "$month/$day/$year"; $dataOK=0; %FORM = ParseForm(); if ($FORM{'formname'} ne "") { unless (-e $datapath) { &error("Data path directory not configured correctly in CGI.") +; } } if($FORM{'validate'} ne "") { #if true, check form fields @to_check = split(/,/,$FORM{'validate'}); for($i=0; $i<=$#to_check; $i++) { if( (exists $FORM{"$to_check[$i]"}) && ($FORM{"$to_check[$i]"} + eq "") ) { push(@errorlist,"\"$to_check[$i]\""); } } if (exists $FORM{'email_field'}) { unless(&validateEmail($FORM{$FORM{'email_field'}})) { push(@errorlist, "e-mail address is in an incorrect format +, ie. abc\@url.com"); } } if(@errorlist) { &show_errors(@errorlist); exit(0); } else { &send_email(); } } else { #no error checking to be performed &send_email(); } if($FORM{'redirect_to'}) { print "Location:$FORM{'redirect_to'}", "\n\n"; exit (0); } else { &wrap_up("<center><b><p>Thank you for your interest. We will be r +esponding shortly.</b></center>"); } exit(0); sub error { local ($message) = @_; print "Content-type: text/html", "\n\n"; print <<HTML; <h3>$message</h3> HTML open (SM, "|$mailapp") || die "No sendmail"; print SM "To: $script_admin\n"; print SM "From: $def_from\n"; print SM "Subject: Script having errors.\n\n"; print SM "$0 had errors : \n\n$message\nOS error reports:$!\n"; print SM "HTTP Referer: $ENV{'HTTP_REFERER'}\n"; print SM "Server Name: $ENV{'SERVER_NAME'}\n"; print SM "Document Root: $ENV{'DOCUMENT_ROOT'}\n"; print SM "Remote Addr: $ENV{'REMOTE_ADDR'}\n"; print SM "HTTP User Agent: $ENV{'HTTP_USER_AGENT'}\n"; close (SM); exit(1); } sub mailerror { local ($message) = @_; open (SM, "|$mailapp") || die "No sendmail"; print SM "To: $script_admin\n"; print SM "From: $def_from\n"; print SM "Subject: Script having errors.\n\n"; print SM "$0 had errors : \n\n$message\nOS error reports:$!\n"; print SM "HTTP Referer: $ENV{'HTTP_REFERER'}\n"; print SM "Server Name: $ENV{'SERVER_NAME'}\n"; print SM "Document Root: $ENV{'DOCUMENT_ROOT'}\n"; print SM "Remote Addr: $ENV{'REMOTE_ADDR'}\n"; print SM "HTTP User Agent: $ENV{'HTTP_USER_AGENT'}\n"; close (SM); } sub ParseForm { my (%FORM); my ($buffer, @pairs, $pair, $name, $value); if ($ENV{"REQUEST_METHOD"} eq "POST") { read(STDIN, $buffer, $ENV{"CONTENT_LENGTH"}); } else { $buffer = $ENV{"QUERY_STRING"}; } @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); chomp ($value); # convert plus signs and hex $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; $name =~ tr/+/ /; $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; # Stop people from using subshells to execute commands # Not a big deal when using sendmail, but very important # when using UCB mail (aka mailx). $value =~ s/~!/ ~!/g; if (defined($FORM{$name}) && ($FORM{$name} ne "")) { unless ($value eq "") { $FORM{$name} .= ", $value"; } } else { #Create an array with the names ordered same as from FORM if (!(defined($FORM{$name}))) { push @ordnames, $name; } $FORM{$name} = $value; } } return (%FORM); } sub validateEmail { my ($Email) = @_; ($Email =~ /^[A-Za-z0-9\.,\-_]+\@[\w\d\-_]+(\.[\w\d\-_]+)+$/) ? 1 : + 0; } # validateEmail sub show_errors { local(@errors) = @_; print "Content-type: text/html", "\n\n"; my $error_head = $FORM{'error_head'}; my $error_foot = $FORM{'error_foot'}; if ($error_head ne "" && $error_foot ne "") { # error head and foo +t configured # check to make sure we are only reading files called "*error_ +*.html"... and that they exist if (($error_head =~ /error_head\.html$/) && ($error_foot =~ /e +rror_foot\.html$/) && (-e $error_head) && (-e $error_foot)) { # Standard usable header and footer to encapsulate form us +er errors open (HEAD, "<$error_head") || &error("error head was not +readable"); while (<HEAD>) { print; } close (HEAD); print "<p><ul>\n"; foreach $error (@errors) { print "<li>$error\n"; } print "</ul>"; open (FOOT, "<$error_foot") || &error("error foot was not +readable"); while (<FOOT>) { print; } close (FOOT); } else { &show_vanilla_errors(@errors); &mailerror("Error head and foot files were configured wron +g."); } # error head and foot files checked } else { &show_vanilla_errors(@errors); } # error head and foot configure check } # show_errors sub show_vanilla_errors { local(@errors) = @_; print <<HTML; <html> <head> <title>blah</title> <link rel="stylesheet" href="/other/styles.css" type="text/css"> </head> <body topmargin="0" leftmargin="0" marginwidth="0" marginheight="0" bg +color="#ffffff" background="/images/bg.gif"> <table border="0" cellpadding="16" cellspacing="0" width="425"> <tr> <td width="425"><b>Please use the back button on your browser to corre +ct the following errors/ommissions that we found on the form you subm +itted.</b> <ul> HTML foreach $error (@errors) { print "<li>$error\n"; } print "</ul>\n"; print <<HTML; </td> </tr> </table> </body> </html> HTML } sub send_email { if($FORM{'recipients'} ne "" || $FORM{'recipient'} ne "") { $email_to = $FORM{'recipients'} . " " . $FORM{'recipient'}; # initialize maildata string with datestamp $outmail = "$datestamp\n-----------------------------------\n\n"; # initialize outdata string with datestamp $outdata = "$datestamp\t"; foreach $key (@ordnames) { $value = $FORM{$key}; # get rid of ^M and stuff $value =~ s/\x0d\x0a/ /g; $value =~ s/[\x0a\x0d]/ /g; unless($key eq "recipient" || $key eq "recipients" || $key eq +"subject" || $key eq "redirect_to" || $key eq "validate" || $key eq " +email_field" || $key eq "error_head" || $key eq "error_foot") { $outmail .= "$key:\t\t$value\n"; # add each key and a tab to datastring $outdata .= "$value\t"; } } # open datafile handle if ($FORM{'formname'} ne ""){ $datafile = "$datapath$FORM{'formname'}.txt"; if (-e $datafile) { unless (open(DATAFILE, ">>$datafile")) { &mailerror("Could not append form data to $datafile"); $dataOK=0; } else {$dataOK=1;} } else { unless (open(DATAFILE, ">$datafile")) { &mailerror("Could not create $datafile"); $dataOK=0; } else {$dataOK=1;} } #write datastring to datafile print DATAFILE "$outdata\n"; close(DATAFILE); } # close datafile handle # chop last tab off of datastring $outdata =~ s/(.*)\t$/$1/; #add url of datafile to email if dataurl if ($dataurl ne "" && $FORM{'formname'} ne "") { if ($dataOK == 1) { $outmail .= "\nA tab-delimited text file was saved at:\n"; $outmail .= "$dataurl$FORM{'formname'}.txt\n"; } else { $outmail .= "\nThere were problems adding entry to datafil +e!\n"; $outmail .= "The script admin, $script_admin, was sent an +email about the error.\n"; } } # open sendmail handle open(MAIL, "|$mailapp"); print MAIL "To: $email_to\n"; print MAIL "Subject: $FORM{'subject'}\n"; print MAIL "From: $def_from\n\n"; print MAIL $outmail; close(MAIL); # close sendmail handle }# end recipients IF else { &wrap_up("You were missing the required hidden fields in your +form. See the script admin for the names and values of these fields." +); } } sub wrap_up { local ($message) = @_; print "Content-type: text/html", "\n\n"; print <<HTML; <html><head><Title>On-line form submission</title></head> <h3>$message</h3> </html> HTML exit (0); }

      Thanks,
      -D

        It looks like you need to add next unless $value; to :

        foreach $key (@ordnames) { $value = $FORM{$key}; next unless $value; # added this line # get rid of ^M and stuff $value =~ s/\x0d\x0a/ /g; $value =~ s/[\x0a\x0d]/ /g; unless ( $key eq "recipient" || $key eq "recipients" || $key eq "subject" || $key eq "redirect_to" || $key eq "validate" || $key eq "email_field" || $key eq "error_head" || $key eq "error_foot" ) { $outmail .= qq|$key:\t\t$value\n|; # add each key and a tab to datastring $outdata .= qq|$value\t|; } }

        HTH,
        Charles K. Clarkson