Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


CGI with PERL -  quick start

Posted on 2004-09-16
Medium Priority
Last Modified: 2013-12-25
Hello Experts,

I'm starting with CGI with perl and I need to some hints such as:

1) Write some scripts just for example (I'm not asking you copy and paste scripts here but rather then that help me to create them from beginning)
2) Make them run on my local apache server with debian 3.1 ( apache is runnig now without problem )
3) Some links for goog tutorial pages regarding CGI with perl programming
4) Create small example of connection between my new CGI with some kind of database
5) Recommend some good books for beginners regarding this topic

I got some skills in perl and in some other languages as well such as java,asp,visual basic ... so I will do my best.

thanks for help

Question by:Luxana
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
LVL 14

Accepted Solution

tomaugerdotcom earned 2000 total points
ID: 12078129


and definitely:

www.perl.com and

Next, creating simple Perl scripts. This stuff is mostly covered in the links above, but here are some really important points:

1. on Unix, the first line of your Perl script, the "pound-bang" line, must point to the Perl executable. This is usually /usr/bin/perl, but you need to check your installation to be sure.

First line of every Perl script you write:
#! /usr/bin/perl

2. Whenever you want to print something to a web page or send data to the browser you MUST include the HTTP header information, at the very least the MIME-Type. You only need to do this once, so 85% of the time just get it over with and put it near the beginning of your script:

print "Content-type: text/html\n\n";

If you attempt to print something BEFORE you print this line, you will likely get an error! Something like "Script returned incomplete or incorrect headers";

3. Permissions. If you're sure there are no errors in your Perl script, but you're still getting errors, check the permissions on the file itself. Let's say you have a file called "myscript.pl" in your "cgi-bin" folder and you know there are no errors but it still won't run at all (not even one little bit), then check the permissions on that file. chmod myscript.pl 744. Usually 744 is good enough, but this can vary greatly depending on the server.

4. Seeing your errors. If you're getting errors in your Perl script but you're not able to see what the errors are (for example no matter what the error you always get "Incomplete headers") one thing that's really useful is to use a Perl Module to actually send the error message to your browser window. This is very helpful in debugging scripts. Use CGI::Carp for this.

# Use CGI::Carp to display errors in your browser window
#! /usr/bin/perl

use CGI::Carp qw(fatalsToBrowser);

5. Reading input from a form is easy if you use the Perl Mod called CGI. You can easily read form fields like text fields, radio buttons, picklists etc. Just make sure in your HTML form that you NAME your fields, because you can then use that name in Perl to access the data. So if I have a textfield for the user name: <input type="text" name="username">

And in Perl, at the top of your Perl script:

#! /usr/bin/perl
use CGI::Carp qw(fatalsToBrowser);
use CGI; # this gives you all sorts of good CGI-related methods

my $cgi = new CGI;
my %userInput = %{$cgi->Vars};

# now, you can get your form data from the %userInput hash, like this:
print "Content-type: text/html\n\n"; # don't forget your header! You only need to do this once

print "The User Name is: $userInput{'username'}.";

6. Get used to using 'strict' and don't forget 'my'!! Using strict makes it SLIGHTLY harder to write perfect code because Perl is less forgiving. However, if you allow yourself to write sloppy code, you will be much more likely to have logic errors in your code:

#! /usr/bin/perl

use strict;

$badVar = "test"; # this will generate an error

my $goodVar = "test"; # the first time you use a variable, precede it with "my".

$goodVar .= "ing"; # after that, you're fine.

Well, I hope this helps. That's a pretty big question you asked, but this should get you started.

Good luck.

Tom Auger
LVL 14

Expert Comment

ID: 12078187
Oh yeah, databases. simple answer: use MySQL and use DBI

#! /usr/bin/per

use DBI; # to access your MySQL database

# connect to your MySQL database (substitute appropriate database name, username and password)
my $dbh = DBI->connect("DBI:mysql:database_name", "username", "password") || die ("Couldn't connect to DB: $!");

# create an SQL query to get at some of your data
my $sth = $dbh->prepare("SELECT * FROM customer WHERE country=? AND province=?");

# run the SQL query
$sth->execute('Canada', 'Ontario');

# work with the resulting data
while (my $rowHash = $sth->fetchrow_hashref) {
  print "first name: $rowHash->{'firstname'}  last name: $rowHash->{'lastname'}";

The rest is up to your knowledge of SQL.

Good luck

LVL 10

Author Comment

ID: 12083754
tom this is a quick start? :))) this study for my entire life:))

Just joking today I got some books such as :

CGI Prgramming with Perl ( O'Reilly )
CGI Prigramnng 101 Perl for the World Wide WEB ( Hamilton)
Custom CGI Scripting with Perl
Instant CGI/PERL

so it seems I will not need yor help ( hope ) but just in case I'll keep this question open untill I finish my project if you don't mind.

thanks tom

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

LVL 10

Author Comment

ID: 12223659
HI Tom,

I went throught book and I'm trying to make one of the scripts there using DBI database. This script is address book but I got a problem there with creating query there and I'm not realy clear what I'm doing there. The book wich I'm following have a lot of mistakes so for beginner as I'm it is hell:-) I fixed lots of mistakes by my self using just common sense but my problem is:

Can't call method "prepare" on an undefined value at /usr/lib/cgi-bin/address_book.cgi line 264.

here is part of script and line 264:

my $where_clause;
if ($cgi->param('exactmatch')) {
      $where_clause = join(" and",
                              map ($_
                                    . " = \""
                                    . $criteria{$_} . "\"", (keys %criteria)));
}      else      {
      $where_clause = join(" and",
                              map ($_
                                    . " like \"%"
                                    . $criteria{$_} . "\"", (keys %criteria)));
$where_clause =~ /(.*)/;
$where_clause = $1;

$sql = $sql . " where " . $where_clause if ($where_clause);

my $sth = $dbh->prepare($sql)      # here is line 264
      or die "Cannot prepare: " . $dbh->errstr();

no idea what I'm missing there. Thanks for your help if you need more info please let me know pls....

thanks tom

LVL 14

Expert Comment

ID: 12226596
No problems.

The line my $sth = $dbh->prepare($sql) queries the database using the database handle ($dbh) that you need to set up first. This is usually done somewhere BEFORE this line using something like:

my $dbh = DBI->connect($data_source, $username, $auth);

$data_source is the name of the database (you might need to talk to your server administrator or web service to get the exact information)
$username is the username of the DATABASE user. This is sometimes the same as your logon for your website, but not always. Again, check with you web service provider.
$auth is the password for this username.

so usually the line looks something like:

my $dbh = DBI->connect("DBI:mysql:databaseName", "myUserName", "myPassword");

Replace the stuff in quotes with the appropriate information of course.

And don't forget, near the start of your script, make sure you have

use DBI;

Hope this helps! For more information on the DBI module, check out cpan (www.cpan.org). http://cpan.uwinnipeg.ca/htdocs/DBI/DBI.html


LVL 11

Expert Comment

ID: 12232584
Tom did a great job!
I have nothing else to add - but just to say - tom has set you up for a quick start.
Without that information - you wont go anywhere...
LVL 10

Author Comment

ID: 12232646
yes I know and he did more than gerat job :) that is why http://www.experts-exchange.com/Web/Web_Languages/CGI/Q_21157261.html
and I would like to keep this discusion here and I know that it is beyoud my quick start question and try to somehow fix my problem with my script:-)

thanks Tom

LVL 14

Expert Comment

ID: 12243678
Thanks guys. I appreciate it - it makes a big difference when people appreciate a detailed answer.

Best of luck!


Featured Post

Certified OpenStack Administrator Course

We just refreshed our COA course based on the Newton exam.  With 14 labs, this course goes over the different OpenStack services that are part of the certification: Dashboard, Identity Service, Image Service, Networking, Compute, Object Storage, Block Storage, and Orchestration.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

719 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question