Jada Pinks Jada Pinks - 1 month ago 11
Perl Question

PERL CGI: How to fix split function with reading/displaying data on a table?

The items in the text file are separated with a pipe symbol "|". The CGI file below will display the items in a table under their designated labels. Please see this Table Output, that's what I have. How do I fix so the items are in their designated columns and not just in one? There's no MySQL or SQL to hold the data, just a text file

#!/usr/bin/perl -w
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
use strict;
use warnings;
print "Content-type: text/html\n\n";

print "<TABLE BORDER>\n";
print "<TR><TH>SKU Code<TH>Name<TH>Description<TH>Price";

open ( ORDERS, "inventory.txt" ) or die "Error opening file, $!";
while(<ORDERS>) {
print "<TR>\n";
print "<TD>";
my @fields=split(/\<\*\>/);
print join(`<TD>`,@fields);
print "</TR>";
}
close ORDERS;
print "</TABLE>";


Here is the CGI File that was used to store the items to the text file

#!/usr/bin/perl -w
use strict;
use warnings;
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
print "Content-type: text/html\n\n";
my $sku = param('sku_code');
my $cust = param('customer');
my $description = param('description');
my $selling = param('price');
my $price = sprintf("\$%.2f");

print <<HERE;
<HTML>
<BODY>
<H3>Here is your order...please check</H3>
SKU: $sku<br>
Name: $cust<br>
Description: $description<br>
Selling Price: $price<br>
HERE
open (ORDERS, ">>inventory.txt") or die "File error, $!";

print ORDERS "$sku|$cust|$description|$price\n";
close ORDERS;

Answer

Something like this will work.

# Best practice: three-arg open() and lexical filehandle
open my $order_fh, '<', 'inventory.txt' or die "Error opening file, $!";

while(<$order_fh>) {
  print "<TR>\n";
  print '<TD>' . join('</TD><TD>', split /\|/) . "</TD>\n";
  print "</TR>\n";
}

close $order_fh;

This code looks rather familiar. Please consider the advice I gave there about using a templating system.

Some other comments on your code:

  • use warnings replaces -w. You don't need both.
  • Use header() (from CGI.pm) to print the header.
  • my $price = sprintf("\$%.2f") - this looks wrong!
  • You really need to add some file locking.
  • Your HTML looks like it's from 1995. We tend to close elements these days.
Comments