View Full Version : Resolved Need help understanding code

04-06-2010, 09:42 PM
I have this code that I found and would like to modify to meet my needs, however I am having trouble understanding a portion of the code and there was no explanation given on the site where I found it. Below is the code:

use CGI qw(:standard);

$regfile = '../public_html/perl/registrations.tsv';

print header;

if(param()) {
$name = param('name');
$email = param('email');
$food = param('food');
if(ok()) {
open(REG,">>$regfile") or fail();
print REG "$name\t$email\t$food\n";
print <<END;
<title>Thank you!</title>
<h1>Thank you!</h1>
<p>Your fake registration to Virtual Nonsense Party
has been recorded as follows:</p>
<p>Name: $name</p>
<p>E-mail: $email</p>
<p>Food preference: $food</p>
exit; } }

%labels = (
'' => 'Food preference (select one):',
'Fish sticks' => 'Fish sticks',
'Falafel' => 'Falafel',
'no food' => 'None (i.e., will not eat)' );

print start_form, 'Fake registration to virtual party',br,
'Name: ', textfield('name'), br,
'E-mail: ', textfield('email'), br,
radio_group(-name=>'food', -values=>\%labels, -linebreak=>'true',
submit, end_form;

sub fail {
print "<title>Error</title>",
"<p>Error: cannot record your registration!</p>";
exit; }

sub ok() {
$fine = 1;
if(!$name) { print 'Your name is required!', br; $fine = 0; }
if(!$email) { print 'Your E-mail address is required!', br; $fine = 0; }
elsif(!($email =~ m/\@/))
{ print 'An E-mail address must contain the @ character!', br;
$fine = 0; }
if(!$food) { print 'A food preference (even if none) is required!',
br; $fine = 0; }
if(!$fine) { print 'Please fix the data and resubmit', hr; }
return $fine; }

What I can't seem to understand is the sub ok(). It is called with this line if(ok()) {, but I can't understand what is happening and why it works as far as checking input. I don't understand the variable $fine or how it affects the call. If anyone can give a brief explanation I would greatly appreciate it.

04-06-2010, 10:48 PM
$fine is just a flag value. The sub is going to return the value of $fine (either zero or one only), depending upon conditions, which is the same as false or true in the if statement. Apparently, ok() is just checking for the presence of the params and whether the $email argument has a certain format.

04-06-2010, 11:06 PM
Thanks Tom