Transcription of Perl and CGI (Common Gateway Interface) - USNA
1 25 perl and CGI(CommonGatewayInterface)Objectives To understandbasicPerl programming. To understandthe CommonGateway interface . To understandstringprocessingand regularexpressionsin perl . Tobeable to read and writecookies. Tobeable to constructprogramsthat is the commonair that bathesthe WhitmanThe longest part of the journey is said to be the passingof our gates to the gloriousand them we pass out into adventureandsunshine, to them,alas! we M. ForsterTherecomes a time in aman s life when to get wherehehasto go ifthereare no doorsor windows hewalksthrougha oughtto be able to show that you can do it agood dealbetterthan anyoneelse with the regular tools before youhave alicenseto bring in your own and CGI (CommonGatewayInterface) IntroductionPracticalExtractionandReport Language( perl )
2 Is one of the most widelyused languag-es for Web begandevelopingthis high-levelprogramminglanguagein 1987whileworkingat initialintentwas to createaprogramminglanguageto monitorlargesoftwareprojectsand createalanguagethat wouldbe morepowerfulthan shell scriptingand moreflexiblethan C, alan-guagewith rich text-processingcapabilitiesand, mostof all, alanguagethat wouldmakecommonprogrammingtasksstraightf orwardand this chapter,we discussPerl examineseveralpracticalexamplesthat use perl for (CGI)is a standardinterfacethroughwhichusersintera ctwith applicationson Web ,CGI providesa way for clients( ,Webbrowsers)to interfaceindirectlywith applicationson the Web is aninterface,it cannotbe programmeddirectly;a scriptor executableprogram(commonlycalledaCGIscri pt)must be executedto interactwith it.
3 WhileCGI scriptscan be writtenin manydifferentprogramminglanguages, perl is commonlyused becauseof its power,itsflexibilityand the availabilityof interactionbetweenclientand serverwhenthe clientrequestsadocumentthat referencesaCGI ,CGI scriptsprocessinformation( ,a search-enginequery,acredit-cardnumber)ga theredfromaform. For example,aCGI scriptmightverifycredit-cardinformationa nd notifythe clientof the results( ,acceptedor rejected).Permissionis grantedwithinthe Web server(usuallyby theWeb-masteror the authorof the Web site) for specificprogramson the serverto be typicallydesignatedwith acertainfilenameextension( ,. )or locatedwithina specialdirectory( ,cgi-bin).
4 Afterthe applicationoutputissent to the serverthroughCGI,the resultsmay be sent to the the clientis usuallyan HTMLor XHTML document,but may containimages,streamingaudio,MacromediaF lashfiles (see Chapters17 18),XML(see Chapter20), and so to Connectto ResourcesSummary Terminology Self-ReviewExercises Answersto Self-ReviewExercises Exercises846 perl and CGI (CommonGatewayInterface)Chapter25 Applicationstypicallyinteractwith the user the streamof informationreceivedby aprogramfrom a user, typ-icallythroughthe keyboard,but also possiblyfrom afile or the informationstreampresentedto the user by an application;it is typicallydis-playedon the screen,but may be printedor writtento CGI scripts,the standardoutputis redirected(orpiped)
5 Throughthe CommonGatewayInterfaceto the serverand then sent over the Internetto aWeb browserfor the server-sidescriptis programmedcorrectly,the outputwill be readableby ,the outputis an HTMLor XHTML documentthat is renderedby PerlWiththe adventof the WorldWideWeb and Web browsers,the Internetgainedtremen-dous greatlyincreasedthe volumeof requestsusersmadefor informationfrom Web becameevidentthat the degreeof interactivitybetweenthe user andthe serverwouldbe powerof the Web residesnot only in servingcontenttousers,but also in respondingto requestsfromusersand such communicationalreadyexistedthroughCGI. Mostof the informationuserssend to serversis text; thus perl was alogicalchoicefor programmingthe serversideof possessessimple,yet powerful,text-processingcapabilitiesand is arguablythe most popularCGI perl community,headedby Wall(whocurrentlyworksfor O Reilly&Associatesas aPerl developerandresearcher),continuouslywork sto evolvethe language,keepingit competitivewith newerserver-sidetechnologies,such as PHP (see Chapter26).
6 To run the perl scriptsin this chapter, perl mustfirst be installedon your the industry-standardPerl distributionfor Windows,Solarisand Linuxplat-formsand is availableas afree be find informationonobtainingand installingPerl on path of a and CGI (CommonGatewayInterface)847 PrintingaLine of presentsa simplePerl programthat writesthe text"Welcometo perl !"tothe programdoes not interactwith the CommonGatewayInterfaceand there-fore is not aCGI initialexamplesare command-lineprogramsthat illustratefun-damentalPerl 3 use the Perlcommentcharacter(#) to instructthe interpreterto ignoreeverythingon the currentline followingthe#.This syntaxallowsprogrammersto writedescriptivecommentsin their exceptionto this rule is the shebang con-struct(#!)
7 Inline 1. On UNIX systems,this line indicatesthe path to the perl interpreter( ,#!/usr/bin/ perl ). On othersystems( ,Windows),the line may be ignoredormay indicateto the server( ,Apache)that aPerl programfollowsthe all serversrequirethe shebang construct(#!), it is good practiceto includeitfor systemsrequirethat the shebangconstructindicatethe path to the perl path is incorrect,the programmightnot run. For Windows,this path is normally#!C:\ perl \bin\ Unix,the path is normally#!/usr/ you are un-sure wherethe perl interpreteris, do a searchforperland use the path foundin the comment(line 2) indicatesthat the file nameof the programfile namestypicallyend with programcan be executedby runningthe perl interpreterfromthe commandprompt( ,the CommandPromptinWindows2000/XPor the MS-DOSP romptin olderversionsof Windows).
8 Referto Run-ning aPerl Script later in this sectionto learnmoreabouthow to executethis 5calls functionprintto writetext to the that becausePerl is casesensitive,writingPrintorPRINT insteadofprintyieldsan text"Welcometo perl !\n"is enclosedin quotesand is last portionof the string the newlineescapesequence,\n movesthe outputcursorto the next line. The semicolon(;)at the end of line 5 terminatesthe perl that the argumentpassedto func-tionprint( , the stringthat we wish to print)is enclosedin parentheses().The paren-thesesare not required;however,we suggestthat you use parenthesesas oftenas possiblein your programsto this example,we use parenthesesto indicatewhatwe want will demonstratethe use of parenthesesthroughoutthe # #Afirstprogramin perl !
9 Fig. program.#!C:\ perl \bin\perlprint("Welcome to perl !\n");848 perl and CGI (CommonGatewayInterface) terminatea statementwith a;is a syntaxerror in most ScriptTo , we must first open the theOpen:text opensthe the commandprompt,typecdexamplesFolderwheree xamplesFolderis the full path of the foldercontainingthe Chapter25 examples( ,C:\IW3 HTP3\examples\ch25examples). This folderpath shouldnow appeartothe left of the blinkingcursorto indicatethat any commandswe type will be executedinthat the the the ,you couldtypeperl-w perl interpreterto outputwarningsto the screenif it finds potentialbugsin your Windowssystems,aPerl scriptmay also be executedby doubleclickingits programicon.
10 The programwindowclosesautomaticallyonce the scriptterminates,and any screenoutputis lost. For this reason,it is usuallybetterto run a scriptfrom the scriptfrom the commandline, alwaysuse ,theprogrammay seem to executecorrectlyeven thoughthere is actuallysomethingwrongwith thesourcecode. The-woptiondisplayswarningsencounteredwh ile executingaPerl Variablesand DataTypesPerl has built-indata types(Fig. )that representdifferentkindsof data. Note that eachvariablenamehas a For example,the$char-acter specifiesthat the variablecontainsascalarvalue( , strings,integernumbers,float-Data typeFormatforvariablenamesof this typeDescriptionScalar$scalarnameCan be a string,an integer number,afloating-pointnumberor a @arraynameAn orderedlist of scalarvariablesthat can be accessedusinginteger unorderedset of scalarvariableswhosevalues areaccessedusinguniquescalarvalues ( , strings) data and CGI (CommonGatewayInterface)849ing-pointnumb ersand references).