Web Programming Languages

Perl Source Code: fwrite.pl

#!/usr/bin/perl
use CGI qw(:standard);
use common;

#----------------------------------------------------------
#   The Web Language Project
#   Mark Brautigam
#   May-June 2015
#   http://www.mixed-up.com/markb/
#----------------------------------------------------------

myUtils::headers1();
myUtils::headers2();
print myUtils::sidebar ("perl", "fwrite", "pl");
  
print <<header;
  <div id='content'>
    <h2>Perl: Form Handling and Write to File</h2>
header

  print_form();

  #----------------------------------------------------
  #  The main Perl code is here.
  #----------------------------------------------------
  if (param ('submit') eq 'Add' && formHasData()) {

    open (my $fh, '>>', "../data/courses.txt");
    print $fh param('college') . "|" . param('dept') . "|" . param('course') . "|" . param('desc') . "\n";
    close ($fp);

    print_feedback();
  }

print <<foot;
    <p><a href='fread.pl'>Show the contents of this file &raquo;</a></p>
    <p><a href='source.pl?f=3'>Show Perl source code &raquo;</a>
  </div>
foot

myUtils::footers();

  #----------------------------------------------------
  # Functions

  #----------------------------------------------------
  sub print_feedback
  #----------------------------------------------------
  {
    print ( "<p>The following data was entered in the data file: </p>\n");
    print ( "<table class='results'>\n");
    print ( "  <tr><td>College</td><td>" . param('college') . "</td></tr>\n");
    print ( "  <tr><td>Department</td><td>" . param('dept') . "</td></tr>\n");
    print ( "  <tr><td>Course #</td><td>" . param('course') . "</td></tr>\n");
    print ( "  <tr><td>Course name</td><td>" . param('desc') . "</td></tr>\n");
    print ( "</table>\n");
  }

  #----------------------------------------------------
  sub print_form
  #----------------------------------------------------
  {
print <<endform;
    <form name='coursesform' action='fwrite.pl' method='POST'>
      <fieldset>
      <legend>Add a course</legend>
      <table>
        <tr><td>College:</td><td><input type='text' name='college' /></td></tr>
        <tr><td>Department:</td><td><input type='text' name='dept' /></td></tr>
        <tr><td>Course #:</td><td><input type='text' name='course' /></td></tr>
        <tr><td>Course name:</td><td><input type='text' name='desc' /></td></tr>
        <tr><td></td><td><input type='submit' id='submit' name='submit' value='Add' /></td></tr>
      </table>
      </fieldset>
    </form>
endform
  }

  #----------------------------------------------------
  sub formHasData
  #----------------------------------------------------
  {
    @formParams = ( 'college', 'dept', 'course', 'desc' );
    foreach $p (@formParams) {
      if (myUtils::trim(param($p)) ne "") {
        return 1;
      }
    }
    return 0;
  }