Scripting Languages
Scripting Languages
2023-24
SCRIPTING LANGUAGES
(R20A0515)
LECTURE NOTES
ARTIFICIAL INTELLIGENCE
&
MACHINE LEARNING
SCRIPTING LANGUAGES
(R20A0515)
LECTURE NOTES
Prepared by
MRS. PRIYA ANIKET GHUGE,
ASSISTANT PROFESSOR
Department of Computational Intelligence
Artificial Intelligence and Machine Learning
Vision
To be a premier centre for academic excellence and research through innovative interdisciplinary
collaborations and making significant contributions to the community, organizations, and society as a
whole.
Mission
QUALITY POLICY
❖ To provide sophisticated technical infrastructure and to inspire students to reach their full potential.
❖ To provide students with a solid academic and research environment for a comprehensive learning
experience.
❖ To provide research development, consulting, testing, and customized training to satisfy specific
industrial demands, thereby encouraging self-employment and entrepreneurship among students.
MALLAREDDYCOLLEGEOFENGINEERINGANDTECHNOLOGY
COURSEOBJECTIVES:
Thiscoursewillenablestudentsto
1. Tostudythebasics ofscriptinglanguages likeJavascript,Perl, PHPand Ruby
2. TounderstandtherequirementsofScriptingLanguages
3. ToidentifytheusesofScriptingLanguages
4. Tointroduce in-depthknowledgeof programmingfeatures ofPerland PHP.
5. TostatetheimplementationandapplicationsofScripting.
UNIT- I
IntroductiontoScriptsandScriptingLanguages–
ScriptsandPrograms,UsesforScriptingLanguages,WebScripting.
JavaScript:Variables,DataTypes,Operators,Conditionalstatements,Loops,Arrays,Functions,Obje
cts-Predefinedobjects,Accessingobjects,ObjectMethods.
UNIT- II
JavaScript programmingofreactivewebpageselements:
JavaScriptEvents-Mouseevents,Keyboardevents,Formevents,windowevents, Eventhandlers,
Frames,Formobject,JavaScriptFormValidation.
UNIT-III
PERL :Data Types, Variables, Scalars, Operators, Conditional statements , Loops, Arrays
,Strings ,Hashes,
Lists,Built-inFunctions,Patternmatchingandregularexpressionoperators.
UNIT-IV
PHP:DataTypes,Variables,Operators,Conditionalstatements,Loops,Arrays-
IndexedArray,Associative
Array, StringFunctions, Functions-ParameterizedFunction,CallByValue, allByReference,File
Handling,
PHPFormhandling.
UNIT- V
Ruby:Datatypes,Variables,Operators,Conditionalstatements,Loops,Methods,Blocks,Modules,Arrays
,Strings,Hashes,FileI/O,RubyForm handling.
2
TEXTBOOKS:
1. TheWorldofScriptingLanguages,DavidBarron,WileyPublications.
2. LearningPHP, MySQL, JavaScript, CSS&HTML5:AStep-by-
StepGuidetoCreatingDynamicWebsites3rdEdition,O’ReillyPublications
REFERENCEBOOKS:
1. TheRubyProgrammingLanguage,DavidFlanaganandYukihiroMatsumoto,O’ReillyPublications.
2. BeginningJavaScriptwithDomscriptingandAJAX,RussFerguson, ChristianHeilmann,Apress.
3. ProgrammingPerl,LarryWall,T.ChristiansenandJ.Orwant,O’Reilly,SPD.
4. OpenSourceWebDevelopmentwithLAMPusingLinuxApache, MySQL, PerlandPHP,
J. Leeand B. Ware(AddisonWesley)PearsonEducation.
COURSEOUTCOMES:
The students will beable:
1. Comprehendthedifferences
betweentypicalscriptinglanguagesandtypicalsystemandapplication
programminglanguages.
2. Toimplementthedesignofprogramsforsimpleapplications.
3. TowriteandapplyPerl&PHP scripts.
4. Gainknowledge of thestrengthsandweaknessof Perl, andRuby.
5. Tocreate software systemsusingscriptinglanguages such asPerl,PHP,and Ruby.
3
INDEX
WebScripting 7
JavaScript–Variables &DataTypes 8
Operators 9
I Controlstructures 12
Arrays 16
Functions 17
Objects 18
JavaScriptEvents 21
Eventhandlers 25
Frames 26
II
Formobject 27
JavaScriptFormValidation 36
PERL 38
Data Types 38
Variables,Scalars 39
Operators 42
III Conditionalstatements 46
Loops 49
Arrays 52
Hashes 54
Strings 57
Lists 59
Built-inFunctions 59
Patternmatchingand regular expression operators 60
4
PHP- Variables 63
Data Types 63
Operators 64
Conditionalstatements 67
Loops 69
IV Arrays 69
StringFunctions 70
Functions 71
FileHandling 73
PHP Formhandling 74
Ruby-Datatypes 76
Variables 77
Operators 77
Conditionalstatements 80
Loops 81
V Methods,Blocks,Modules 82
Arrays 85
Strings 86
Hashes 86
FileI/O 87
Ruby Formhandling 90
5
UNIT-I
ScriptingLanguages
Scripting languages, as the name suggests, is a programming language that
supportsscripts. A scripting language binds a set of software components that
collaborate tosolvea particular problem. Scripting assumes the existence of powerful
componentsandprovidesthemeanstoconnectthemtogether.Scriptinglanguagesaregluela
nguagesthatintegratetheexecutionofsystemutilitiesincludingcompilers;commandlineint
erpretation;shell-basedprogramming;andexecutionofcodeswritteninweb-
basedlanguages.Thepurposeofascriptinglanguageisthedevelopmentofapplicationsbyplu
ggingexistingcomponentstogetherandtheygenerally favor high-level programming
over execution speed. Scripting is used in avariety of applications, and scripting
languages are correspondingly diverse. Python
isapowerfulscriptinglanguageforcomplexsysteminvolvingoperatingsystem,networks,an
dweb-basedprogramming.
ProgrammingLanguages
Aprogramminglanguageisanorganizedwayofcommunicatingwithacomputer,suchthatth
ecomputerbehavesaccordingtotheinstructionsgivenbytheprogrammer.Aprogrammingla
nguageisanartificialformalisminwhichalgorithmscanbeexpressed.Inthemodernera,thepr
oblemstobesolvedbycomputerslieindifferentproblemdomainssuchasscientificcomputin
g,databaseprogramming,businessapplications,processautomation,andweb-
basedapplications.Allthesedomainsarequitedifferentwithvariedrequirements.Aprogram
minglanguageisaspecificsetofinstructionsgiventoacomputerinalanguagethatthecompute
runderstandstoperformspecifictasks.Today’sprogramminglanguagesaretheproductofde
velopmentthatstartedinthe1950s.Thetermprogramminglanguagesusually refer to high-
level languages such as C++, Java, Ada, Pascal, and
FORTRAN.Usesforscriptinglanguages
Thefunctionsandapplicationsofscriptinglanguagesvarybasedonthetypeof
scriptinglanguageyou'reusing.Therearemanyusesforscriptinglanguages,including:
• Task automation: Programmers often use scripting languages to automate
taskexecution within a runtime environment. This involves writing code that
allowsindividualstousesoftwaretocompleterepetitive,predictableandstraightforw
ardtasks,suchaspayingbillsfromanaccountandsendingnotifications viaemail.
• Content display for web applications: Programmers use scripting to
ensureprograms run correctly on the server and display the functional and
interactivecontent onawebpage,suchasimagesandlinks.
6
• Commandsequences:Manyprogrammersapplyscriptinglanguagestocondenseco
mmandsequences,allowingtheprogramtorunfasterandimprovingthefunctionality
ofparentapplications.
• Data extraction: Programmers use scripting languages to pull data from
datasets,suchasindataanalysis,researchandstatistics.
• Dynamic web apps: Programmers use a variety of scripting languages to
powerwebpages and applications on the server side with efficient code and
clearinstructions for displaying dynamic content,which is data that changes
basedon theuser'sbehavior orpreferences.
• System administration: When administrators want to generate and pull
data,guideuserqueriesandimprove systems,they usescriptinglanguages.
• Game modding: Game modification creators use scripting languages to
makecustom content for games with unique functionality and designs that
improveregulargameplay.
WebScripting
• The process of creating and embedding scripts in a web page is known as web-
scripting. A script or a computer-script is a list of commands that are
embeddedin a web-page normally and are interpreted and executed by a certain
programorscriptingengine.
• Scriptsmaybewrittenforavarietyofpurposessuchasforautomatingprocessesonaloc
al-computerortogeneratewebpages.
• The programming languages in which scripts are written are called
scriptinglanguage,therearemanyscriptinglanguagesavailabletoday.
• Common scripting languages are VBScript, JavaScript, ASP, PHP, PERL,
JSPetc.
JavaScript
JavaScript(JS)istheworld’smostpopularlightweight,interpretedcompiledprogramming
language. It is also known as a scripting language for web pages. It canbe used for
Client-sideas well as Server-sidedevelopments.JavaScript is the mostpopular and
hence the most loved language around the globe.Apart from this,
thereareabundantreasonstolearnit.
Beloware a listingof few important points:
• No need of compilers: Since JavaScript is an interpreted language, therefore
itdoesnotneedanycompilerforcompilations.
• Used both Client and Server-side: Earlier JavaScript was used to build client-
side applications only, but with the evolution of its frameworks namely
Node.jsandExpress.js,it isnow widely usedforbuildingserver-side applications
too.
7
• Helps to build a complete solution: As we saw, JavaScript is widely used
inboth client and server-side applications, therefore it helps us to build an end-
to-endsolutiontoagivenproblem.
• Used everywhere: JavaScript is so loved because it can be used anywhere.
Itcanbeusedtodevelop websites,gamesormobile apps,etc.
• Huge community support: JavaScript has a huge community of users
andmentorswho lovethis languageandtakeit’s legacyforward.
Variables
Variablesare containersfor storingdata (storingdatavalues).
DeclareaJavaScriptVariable:
• Usingvar
• Usinglet
• Usingconst
declaredwiththevarkeyword:
var
x=5;var
y=6;varz=
x+y;
o/p: The valueof z is: 11
In this example, x, y, and z, are variables, declared with the let
keyword:let x=5;
lety=6;let
z=x+y;
o/p: The valueof z is: 11
If you want a general rule: always declare variables with
const.If you thinkthe valueofthe variable canchange,uselet.
const
p1=5;constp2=
6;Lettot=p1=p
2;
o/p: Thetotal is: 11
Datatypes
• Numbers: Represent both integer and floating-point numbers. Example: 5,
6.5,7 etc.
• String:A string isasequenceofcharacters.InJavaScript,stringscanbeenclosed
within the single or double quotes. Example: “Hello GeeksforGeeks”etc.
• Boolean:Representalogicalentityand canhavetwovalues:trueor false.
• Null: This type has only one value: null. It is left intentionally so that it
showssomethingthatdoesnotexist.
• Undefined:Avariablethathasnotbeen assignedavalue isundefined.
8
• Symbol: Unlike other primitive data types, it does not have any literal form.
Itis abuilt-in objectwhoseconstructorreturnsasymbol-that isunique.
• bigint: The bigint type represents the whole numbers that are larger than 253-
1.To form a bigint literal number, you append the letter n at the end of
thenumber.
• Object: It is the most important data-type and forms the building blocks
formodern JavaScript. We will learn about these data types in detail in
furtherarticles.
Operators
JavaScriptoperatorsaresymbolsthatareusedtoperformoperationsonoperands.Forexampl
e:
1.varsum=10+20;
Here,+isthearithmeticoperatorand
=istheassignmentoperator.Therearefollowingtypesofoperators in
JavaScript.
1. ArithmeticOperators
2. Comparison(Relational)Operators
3. BitwiseOperators
4. LogicalOperators
5. AssignmentOperators
6. SpecialOperators
ArithmeticOperators
Arithmeticoperatorsareusedtoperformarithmeticoperationsontheoperands.Thefollowin
goperators areknown asJavaScript arithmeticoperators.
9
Comparisonoperators
Bitwise operators
10
AssignmentOperators
11
ConditionalStatements
Thereare threeformsof ifstatementinJavaScript.
1. IfStatement
2. Ifelsestatement
3. ifelse ifstatement
Ifstatement
Itevaluatesthecontentonlyifexpressionistrue.ThesignatureofJavaScriptifstatement
isgivenbelow.
if(expression)
{
//contenttobeevaluated
}
<script>v
ar
a=20;if(a
>10){
document.write("valueofa isgreaterthan10");
}
</script>
Outputoftheaboveexample
valueof aisgreaterthan10
If...elseStatement
Itevaluatesthecontentwhetherconditionistrueoffalse.ThesyntaxofJavaScriptif-
elsestatementisgivenbelow.
if(expression)
{
//contenttobeevaluatedifconditionistrue
}
else
{
//contenttobeevaluatedifconditionisfalse
}
<script>var
a=20;if(a%
2==0)
{
12
document.write("aisevennumber");
}
else
{
document.write("aisoddnumber");
}
</script>
Outputoftheaboveexample
aisevennumber
If...elseifstatement
Itevaluatesthecontentonlyifexpressionistruefromseveralexpressions.The
signatureofJavaScriptifelseif statementisgivenbelow.
if(expression1)
{
//contenttobeevaluatedifexpression1istrue
}
elseif(expression2)
{
//contenttobeevaluatedifexpression2istrue
}
elseif(expression3)
{
//contenttobeevaluatedifexpression3istrue
}
else
{
//contenttobeevaluatedifnoexpressionistrue
}
Let’sseethesimpleexampleofifelseifstatementinjavascript.
<script>v
ar
a=20;if(a
==10)
{
document.write("a is equalto 10");
}
elseif(a==15){document.write("aisequalto15");
}
13
elseif(a==20){
document.write("a is equalto 20");
}
else{
document.write("a is not equalto 10,15or 20");
}
</script>
Output:
ais equalto 20
Loops
loopsareusedtoiteratethe piece ofcodeusing for,while,dowhileor for-
inloops.Itmakesthecodecompact.It ismostlyusedinarray.
Thereare four typesof loopsinJavaScript.
1. for loop
2. whileloop
3. do-whileloop
Forloop
Theforloopiteratestheelementsforthefixednumberoftimes.Itshouldbeusedifnumberofite
rationis known.Thesyntax offorloop is givenbelow.
for(initialization;condition;increment)
{
codeto beexecuted
}
<script>
for(i=1;i<=5;i++)
{
document.write(i +"<br/>")
}
</script>
Output:
1
2
3
4
5
14
whileloop
The whileloopiteratestheelementsfortheinfinitenumberoftimes.Itshouldbeused
ifnumber of iteration isnotknown.The syntaxof whileloopisgiven below.
while(condition)
{
code to beexecuted
}
Let’sseethesimpleexampleofwhileloopinjavascript.
<script>
vari=11;
while(i<=15)
{
document.write(i +
"<br/>");i++;
}
</script>
Output:
11
12
13
14
15
dowhileloop
Thedo while loop iterates the elements for the infinite number of times like whileloop.
But, code is executed at least once whether condition is true or false. The
syntaxofdowhileloopis givenbelow.
do{
code to beexecuted
}while(condition);
<script>
var
i=21;do{
document.write(i +
"<br/>");i++;
}while(i<=25);
</script>
Output:
15
21
22
23
24
25
Arrays
arrayisanobjectthatrepresentsacollectionofsimilartypeofelements.
The syntaxofcreatingarray
vararrayname=newArray();
Here, new keyword is used to create instance of
array.Let's seethe example ofcreatingarraydirectly.
<script>
var i;
var emp = new
Array();emp[0]="Arun
";
emp[1]="Varun";
emp[2] ="John";
for
(i=0;i<emp.length;i++){document.write(emp[i]
+"<br>");
}
</script>
Outputoftheabove example
Arun
Varun
John
16
Functions
functionsareusedtoperformoperations.WecancallJavaScriptfunctionmanytimesto
reusethecode.
Advantage ofJavaScriptfunction
TherearemainlytwoadvantagesofJavaScriptfunctions.
1. Codereusability:Wecancallafunctionseveraltimessoitsavecoding.
2. Lesscoding:Itmakesourprogramcompact.Wedon’tneedtowritemanylines
ofcodeeachtimetoperformacommon task.
FunctionSyntax
The syntaxof declaringfunction isgivenbelow.
1. functionfunctionName([arg1,arg2, ...argN]){
2. //code to be
executed3.}
Let’sseethesimpleexampleoffunctioninJavaScriptthatdoesnothasarguments.
<script>functio
nmsg(){
alert("hello!thisismessage");
}
</script>
<inputtype="button"onclick="msg()"value="callfunction"/>
FunctionArguments
Wecancallfunctionbypassingarguments.Let’sseetheexampleoffunctionthathasoneargu
ment.
<script>
function
getcube(number){alert(number
*number*number);
}
</script>
<form>
<inputtype="button"value="click"onclick="getcube(4)"/>
</form>
17
FunctionwithReturnValue
Wecancallfunctionthatreturnsavalueanduseitinourprogram.Let’sseetheexample
offunctionthatreturnsvalue.
<script>
functiongetInfo(){
return "hello javatpoint!How r u?";
}
</script>
<script>document.write(getIn
fo());
</script>
o/p:hellojavatpoint!Howru?
JavaScriptObjects
AjavaScriptobjectis anentity havingstateand
behavior(propertiesandmethod).Forexample:
car,pen,bike,chair,glass,keyboard,monitoretc.
JavaScript is an object-based language. Everything is an object in
JavaScript.JavaScriptistemplatebasednotclassbased.Here,wedon'tcreateclasstogettheob
ject.But,wedirectcreateobjects.
CreatingObjects
BycreatinginstanceofObject
Thesyntaxof creatingobject directly isgivenbelow:
1.varobjectname=newObject();
Here,newkeywordis usedto
createobject.Let’sseetheexampleofcreatingobject
directly.
1. <script>
2. var emp=new
Object();3.emp.id=101;
4. emp.name="RaviMalik";
5. emp.salary=50000;
6. document.write(emp.id+""+emp.name+""+emp.salary);
7. </script>
o/p:101Ravi50000
Accessingobjects
Acommonway toaccess thepropertyof an objectisthedotproperty accessorsyntax:
expression.identifier
expressionshouldevaluatetoanobject,andidentifieristhenameofthepropertyyou'd
liketoaccess.
18
Predefined
objectsFundamentalobjects:
• Object
• Function
• Boolean
• Symbol
Errorobjects
Errorobjectsareaspecialtypeoffundamentalobject.TheyincludethebasicErrortype,
aswellasseveralspecializederrortypes.
• Error
• AggregateError
• EvalError
• RangeError
• ReferenceError
Numberanddateobjects
Thesearethebaseobjectsrepresentingnumbers,dates,andmathematicalcalculations
.
• Number
• BigInt
• Math
• Date
Textprocessingobjects
Theseobjectsrepresentstringsandsupportmanipulatingthem.
• String
• RegExp
Keyedcollections
These objects represent collections which use keys. The iterable
collections(MapandSet)containelementswhichareeasilyiteratedintheorderofinser
tion.
• Map
• Set
• WeakMap
• WeakSet
19
Objectmethods
20
UNIT-II
Events:
HTMLeventsare"things"thathappentoHTMLelements.
WhenJavaScriptisusedinHTMLpages,JavaScriptcan"react" ontheseevents.
HTMLEvents
AnHTMLeventcan be somethingthebrowser does,or somethinga user
does.Herearesomeexamples ofHTMLevents:
• AnHTMLweb page has finishedloading
• AnHTMLinputfield was changed
• AnHTMLbuttonwas clicked
Often,wheneventshappen,youmaywanttodosomething.JavaScri
ptletsyouexecute codewhen eventsaredetected.
HTMLallowseventhandlerattributes,withJavaScriptcode,tobeaddedtoHTMLelements
.
Withsinglequotes:
<element event='some
JavaScript'>With doublequotes:
<elementevent="someJavaScript">
In the following example, anonclickattribute (with code), is added
toa<button> element:
<buttononclick="document.getElementById('demo').innerHTML=Date()">Thetimeis?
</button>
Mouseevents:
EventsthatoccurwhenthemouseinteractswiththeHTMLdocumentbelongstotheMouseEv
ent Object.
21
22
Keyboardevents
Eventsthatoccurwhenuserpressesakeyonthekeyboard,belongstotheKeyboardEventObje
ct.
23
24
Eventhandlers
To allow you to run your bits of code when these events occur, JavaScript provides
uswith event handlers. All the event handlers in JavaScript start with the word on,
andeach event handler deals with a certain type of event. Here’s a list of all the
eventhandlers in JavaScript, along with the objects they apply to and the events that
triggerthem:
25
Frames
• FrameobjectrepresentsanHTMLframewhichdefinesoneparticularwindow(frame)
withinaframeset.
• Itdefines thesetof framethatmakeupthebrowserwindow.
• Itisapropertyofthewindowobject.
Syntax:<frame>
• Ithas noend tagbuttheyneed tobe closed properly.
• ItisanHTMLelement.
• Itdefines a particular areainwhich another HTMLdocumentcanbe displayed.
• Aframe shouldbe usedwithina<FRAMESET>tag.
26
FormObject
form object is a Browser object of JavaScript used to access an HTML form. If a
userwants to access all forms within a document then he can use the forms array. The
formobjectisactuallyapropertyofdocumentobjectthatisuniquelycreatedbythebrowser for
each form present in a document. The properties and methods associatedwith form
object are used to access the form fields, attributes and controls associatedwith forms.
PropertiesofFormObject:
• action
• elements[]
• encoding
• length
• method
• name
• target
• button
• checkbox
• FileUpload
• hidden
• password
action:
action property of form object is used to access the action attribute present in
HTMLassociated with the <form> tag. This property is a read or write property and its
valueis astring.
elements[]:
elementspropertyofformobjectisanarray usedtoaccessany
elementoftheform.Itcontainsallfieldsandcontrolspresentintheform.Theusercanaccessan
yelementassociated with the form by using the looping concept on the elements
array.encoding:
Theencodingpropertyofaformobjectisusedtoaccesstheenctypeattributepresent
inHTMLassociatedwiththe<form>tag.Thispropertyisareadorwritepropertyand its value
is a string. This property helps determine the way of encoding the formdata.
length:
lengthpropertyofformobjectisusedtospecifythenumberofelementsintheform.This
denotesthe length ofthe elements arrayassociatedwith the form.
method:
methodpropertyofformobjectisusedtoaccessthemethodattributepresentinHTMLassociat
edwiththe<form>tag.Thispropertyisareadorwritepropertyand
27
itsvalueisastring.Thispropertyhelpsdeterminethemethodbywhichtheformissubmitted.
name:
nameproperty offormobject denotes theform name.
target:
target property of form object is used to access the target attribute present in
HTMLassociated with the <form> tag. This property denotes the name of the target
windowto whichformitisto besubmittedinto.
button:
The buttonproperty of formobject denotes thebuttonGUIcontrol placed intheform.
checkbox:
checkboxproperty of formobject denotes thecheckboxfield placed intheform.
FileUpload:
FileUploadproperty of formobject denotes thefile uploadfield placed intheform..
hidden:
The hiddenproperty of formobject denotes thehiddenfield placed intheform.
password:
passwordpropertyofformobjectdenotesthe objectthatisplacedasapasswordfieldin
theform.
FormObject
• Formobjectrepresents anHTMLform.
• It is used to collect user input through elements like text fields, check box and
radiobutton,selectoption,textarea,submitbuttons andetc.
28
HiddenObject
• Hidden objectrepresents a hiddeninput field inan HTMLformand itisinvisibletothe
user.
• Thisobject canbe placedanywhere onthewebpage.
• Itisused tosendhiddenformof data toa server.
PasswordObject
29
CheckboxObject
• Checkboxobject represents acheckbox inan HTMLform.
• Itallowstheusertoselect one ormore optionsfromtheavailable choices.
CheckboxObject Properties
30
SelectObject
• Selectobject represents adropdown listinanHTML form.
• Itallowstheusertoselect one ormore optionsfromtheavailable choices.
31
SelectObjectProperties
SelectObjectMethods
OptionObject
• Optionobject represents anHTML<option>element.
• Itisused toadd itemstoa selectelement.
32
<html>
<head>
<scripttype="text/javascript">fu
nctionoptionfruit(select)
{
vara=select.selectedIndex;
varfav=select.options[a].value;if
(a==0)
{
alert("Pleaseselect a fruit");
}
else
{
document.write("YourFavoriteFruitis<b>"+fav+".</b>");
}
}
</script>
</head>
<body>
<form>
ListofFruits:
33
<selectname="fruit">
<optionvalue="0">SelectaFruit</option>
<optionvalue="Mango">Mango</option>
<optionvalue="Apple">Apple</option>
<optionvalue="Banana">Banana</option>
<optionvalue="Strawberry">Strawberry</option>
<optionvalue="Orange">Orange</option>
</select>
<inputtype="button" value="Select"onClick="optionfruit(this.form.fruit);">
</form>
</body>
</html>
Output:
Mango.RadioObject
34
TextObject
Textobject represents asingle-linetextinputfield inanHTMLform.
35
TextareaObject
Textareaobjectrepresents atext-areainan HTMLform.
JavaScriptFormValidation
HTMLformvalidationcan be done byJavaScript.
Ifaformfield(fname)isempty,thisfunctionalertsamessage,andreturnsfalse,toprevent
theformfrombeingsubmitted:
functionvalidateForm(){letx=document.forms["myFor
m"]["fname"].value;if(x==""){
alert("Namemustbefilledout");ret
urnfalse;
}
}
The function can becalled when theformis submitted:
HTMLFormExample
<formname="myForm"action="/action_page.php"onsubmit="return
validateForm()"method="post">Name:<inputtype="text"name="fna
me">
<inputtype="submit"value="Submit">
</form>
36
JavaScriptCanValidateNumericInput
JavaScriptisoftenused tovalidatenumericinput:
37
UNIT-III
Datatypes
TherearedifferentdatatypesavailableinPerlfordifferentpurposes.Someofthemhavebeenp
resentedbelow:
• Boolean
• Integer
• Float
• Array
• String
Unlike other languages such as C++ or Java, Perl does not require defining
variablesalong with a specific data type. The type of a variable is picked based on the
valueassigned toit.
Hereisabrief overviewof thetypes:
Boolean
Boolean data type is used to store true or false values. The numeric value 0 is used
torepresent false, whereas any other numeric value represents true. Let’s look at
thecodebelow:
$false =0; # reutrnsfalse
$true =1;#any values greater or lessthan0returns true
Integer
An integer is a positive or negative whole number. Perl allows you to assign
integerconstants in decimal, hexadecimal, octal or binary numbering systems.
Consider thefollowingcode:
$negative=-3;#negative
$zero =0; # zero(canalsobefalse,if used asaBoolean
$positive=123;#positivedecimal
$zeroPos = 0123; #0 prefix is used to sepcify octal - octal value = 83 decimal $hex
=0xAB;#0xprefix isused tospecifyhexadecimal-hexadecimalvalue =171decimal
$bin=0b1010;#0bprefixisusedtospecify binary-binaryvalue=10decimalprint
$negative," " ,$zero,"" ,$positive," " ,$zeroPos," " ,$hex," ",$bin;
38
Output
-3 0 123 83 171 10
Float
Floatingpointnumbers,doublesorsimplycalled floatsare decimalnumbers.
$float1=1.23;
$float2 =
10.0000001;print
$float1,"
",$float2;Output
1.23 10.0000001
Array
Anarrayislikealistofvalues(similarorofdifferentdatatypes).Thesimplestformof an array
is indexed by an integer, and ordered by the index, with the first elementlying at index
0. We use @ to initiate an array with values enclosed in () pair
ofparenthesis.Lookatthefollowingcode:
@intarray=(1,2,3);
# An array of integers print "@intarray
\n";@floatarray=(1.123,2.356,19.76);
# An array of floats print "@floatarray
\n";@chararray=('a','b','c');
# An array of characters print "@chararray
\n";@mixed =(1,2,3,'a','b','c');
#containsbothcharactersandnumbersprint"@mixed";Out
put
1 2 3 1.123 2.356 19.76 abc12 3 ab c
String
Astringisanarrayof characters.We candeclareastring
usingeithersinglequotes(')ordoublequotes(").
$string1="Aquickbrown fox jumpsover thelazy
dog";print $string1;
Output
Aquickbrownfoxjumps overthe lazydog
Variables
Avariableinanyprogramminglanguageisanamedpieceofcomputermemorytoholdsome
programdata.Variablesare anessential part ofa computerprogram.
You can declare a variable in Perl using a $ sign followed by its name, e.g.,
$myVar.onsiderthefollowingPerlcodewherewestoredatainvariablesanddisplaythemont
he screen.
$string = "This is a
string.";# storesstring
39
$int =5;
#stores aninteger
$float=5.7;
#stores a floatingpointtypevalue
$char='a';
# stores character type
valueprint $string,"\n";
print"An integertype:",$int,"\n";print
"Afloattype:
",$float,"\n";print"Acharactertype:",$
char,"\n";
Output
Thisisa string.An integer type:5Afloat type:5.7Acharacter type:a
scalars
Ascalarisasingleunitofdata.Thatdatamightbeanintegernumber,floatingpoint,acharacter,
astring,aparagraph,oranentirewebpage.
Here is a simple example of using scalar variables
−#!/usr/bin/perl
$age =25; #Anintegerassignment
$name="JohnPaul"; #Astring
$salary=1445.50;
#Afloatingpointp
rint "Age=$age\n";
print "Name =
$name\n";print"Salary=$sal
ary\n";
This will produce the following result
−Age=25
Name = John
PaulSalary =
1445.5NumericS
calars
Ascalarismostofteneitheranumberorastring.Followingexampledemonstrates
the usage of various types of numeric scalars
−#!/usr/bin/perl
$integer=200;
$negative =-300;
$floating=200.340;
$bigfloat=-1.2E-23;
#377octal,same as255decimal
$octal =0377;
40
#FFhex,also255decimal
41
$hexa =0xff;
print "integer =
$integer\n";print "negative =
$negative\n";print "floating =
$floating\n";print "bigfloat =
$bigfloat\n";print
"octal=$octal\n";
print"hexa=$hexa\n";
This will produce the following result
−integer=200
negative=-300
floating =
200.34bigfloat = -
1.2e-23octal=255
hexa =255
StringScalars
Followingexampledemonstratestheusageofvarioustypesofstringscalars.Noticethe
difference between single quoted strings and double quoted strings −#!/usr/bin/perl
$var ="Thisisstringscalar!";
$quote='Iminsidesinglequote- $var';
$double="Thisisinsidesinglequote-$var";
$escape = "This example of escape -\tHello,
World!";print "var=$var\n";
print "quote =
$quote\n";print "double =
$double\n";print"escape
=$escape\n";
This will produce the following result
−var=Thisis stringscalar!
quote=I minsidesinglequote- $var
double = This is inside single quote - This is string
scalar!escape =Thisexampleofescape- Hello,
WorldScalar Operations
YouwillseeadetailofvariousoperatorsavailableinPerlinaseparatechapter,but
herewearegoingtolistdownfewnumericandstringoperations.#!/usr/bin/per
l
$str="hello" ."world"; #Concatenatesstrings.
$num=5+10; #adds twonumbers.
$mul=4* 5; #multiplies twonumbers.
$mix=$str.$num;
#concatenatesstringandnumber.pr
int "str=$str\n";
42
print "num =
$num\n";print "mul =
$mul\n";print"mix=$
mix\n";
This will produce the following result
−str =helloworld
num=15
mul=20
mix=helloworld15
MultilineStrings
If you want to introduce multiline strings into your programs, you can use the
standardsingle quotesasbelow−
#!/usr/bin/perl
$string = 'This
isamultilinestrin
g';
print"$string\n";
Thiswillproduce thefollowingresult−
This is
a
multilinest
ring
Operators
4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator.
Perllanguage supports many operator types, but following is a list of important and
mostfrequently usedoperators−
• Numericoperators
• Stringoperators
• Logicaloperators
• Bitwiseoperators
• Specialoperators
• Comparisonoperators
• Assignmentoperators
Numericoperators
Numeric operators are the standard arithmetic operators like addition (+), subtraction(-
),multiplication(*),division(/)andmodulo (%),etc.
Stringoperators
Stringoperatorsarepositiveandnegativeregularexpressionwithrepetition(=~and
!~)and concatenation( .).
43
StringConcatenationoperator
use
5.010;use
strict;
usewarnings;
my $result = "Hello this is " .
"JavaTpoint.";say$result;
output:
HellothisisJavaTpoint.
StringRepetitionoperator
use
5.010;use
strict;
usewarnings;
my $result = "Thank You " x
3;say$result;
output:
ThankYouThankYouThankYou.
Here, note that on the right of 'x' it must be an
integer.Thereshouldbespaceoneithersideofthe'x'operator.
For example,
$result ="ThankYou"x3;#Thisiscorrect
1.$result ="ThankYou "x3; # This isincorrect
Logicaloperators
Logicaloperatorsgive a Booleanvaluetotheir operands.Theyare (&&,||and or).&&-
>In&&operator,if$ais0,thenvalueof$a&&$bmustbefalseirrespectiveofthevalueof$b.So
perldoesnotbothertocheck$bvalue.Thisiscalledshort-circuit evaluation.
||->In||operator,if$aisnon-zero,thenvalueof$a&&$bmustbetrueirrespectiveofthe
valueof$b.So perldoesnot botherto check$bvalue.
Example:
use
5.010;use
strict;
usewarnings;
$a=0;
$b=12;
my $result1 = $a &&
$b;say$result1;
$a =12;
$b =14;
44
my $result2 = $a ||
$b;say$result2;
Output:
0
12
Bitwiseoperators
Bitwiseoperatorstreattheiroperandsnumericallyatbitlevel.Theseare(<<,>>,&,|,
^,<<=,>>=,&=,|=,^=).
Everynumberwillbedenotedintermsof0sand1s.Initiallyintegerswillbeconverted into
binary bit and result will be evaluated. Final result will be displayed inthe integerform.
Example:
use
5.010;use
strict;
use
warnings;#O
Roperator
my $result1 = 124.3 |
99;say$result1;
#ANDoperator
my $result2 = 124.3 &
99;say$result2;
#XORoperator
my $result3 = 124.3 ^
99;say$result3;
#Shiftoperator
my $result4 = 124 >>
3;say$result4;
Output:
127
96
31
15
Specialoperators
Theauto-increment(++)operatorisaspecialoperatorthatincrementsthenumericcharacter
itselfby1.
Example:
use
5.010;use
strict;
usewarnings;
45
my $num =
9;my$str='x';
$num++;
$str++;
say
$num++;say
$str++;
Output:
10
Y
Comparisonoperators
Thecomparisonoperatorcomparesthevaluesofitsoperands.Theseare(==,<,<=,
>,>=,<=>,!=).
Example:
use
5.010;use
strict;
usewarnings;
say "Enter your
salary:";my$salary=<>;i
f($salary>=20000)
{
say "You areearningwell";
}else{
say"You are not earningwell";
}
Output:
Enter your salary:
15000
Youarenotearningwell
Assignmentoperators
The assignment operator assigns a value to a
variable.These are (=,+=,-=,*=,/=,|=,&=,%=)
Example:
use 5.010;
usestrict;
usewarnings;
$a=20;
my $result1 = $a +=
$a;say$result1;
46
my $result2 = $a -=
10;say$result2;
my $result3 = $a |=
10;say$result3;
my$result4=$a&=10;sa
y$result4;
output:
40
30
30
10
ConditionalStatements
Perlconditionalstatementshelpsinthedecisionmaking,whichrequirethattheprogrammers
pecifiesoneormoreconditionstobeevaluatedortestedbytheprogram, along with a
statement or statements to be executed if the condition isdetermined to be true, and
optionally, other statements to be executed if the conditionis determinedtobefalse.
APerlifstatementconsistsofabooleanexpressionfollowedbyoneormorestatements.
Syntax
The syntax of an if statement in Perl programming language is
−if(boolean_expression){
#statement(s) willexecute ifthegiven conditionistrue
}
Ifthebooleanexpressionevaluatestotruethentheblockofcodeinsidetheifstatement will be
executed. If boolean expression evaluates to false then the first set ofcode after the end
oftheifstatement(after the closingcurlybrace) will be executed.
The number 0, the strings '0' and "" , the empty list () , and undef are all false in
aboolean context and all other values are true. Negation of a true value by !or
notreturns aspecialfalsevalue.
#!/usr/local/bin/perl
$a=10;
# check the boolean condition using if
statementif($a<20){
# if condition is true then print the
followingprintf"aislessthan20\n";
}
print"value ofa is :$a\n";
$a="";
47
# check the boolean condition using if
statementif($a){
# if condition is true then print the
followingprintf"ahasatruevalue\n";
}
print "value of a is :
$a\n";o/p:
ais less than
20value of a is :
10valueofais :
if-else
APerlifstatementcanbefollowedbyanoptionalelsestatement,whichexecuteswhenthebool
eanexpressionisfalse.
Syntax
The syntax of an if...else statement in Perl programming language is
−if(boolean_expression){
#statement(s) willexecute ifthegiven conditionistrue
}else{
#statement(s) willexecuteifthegiven conditionisfalse
}
If the boolean expression evaluates to true, then the if block of code will be
executedotherwiseelseblockofcodewillbeexecuted.
The number 0, the strings '0' and "" , the empty list () , and undef are all false in
aboolean context and all other values are true. Negation of a true value by !or
notreturns aspecialfalsevalue.
#!/usr/local/bin/perl
$a=100;
# check the boolean condition using if
statementif($a<20){
# if condition is true then print the
followingprintf"aislessthan20\n";
}else{
#ifconditionisfalsethenprintthefollowingprintf"
ais greaterthan20\n";
}
print"value ofa is :$a\n";
$a="";
# check the boolean condition using if
statementif($a){
#if conditionis truethenprint the following
48
printf"ahas atrue value\n";
}else{
#ifconditionisfalsethenprintthefollowingprintf"
ahasafalsevalue\n";
}
print"value ofa is :$a\n";
Whentheabove codeisexecuted,itproducesthe
followingresult−aisgreaterthan20
value of ais: 100
a has a false
valuevalueofais:
if-elsif-else
Anifstatementcanbefollowedbyanoptionalelsif...elsestatement,whichisveryusefulto
testthe variousconditionsusingsingleif...elsifstatement.
When usingif,elsif,elsestatementsthere are few pointstokeep inmind.
• Anifcan havezeroor oneelse'sand itmustcome afteranyelsif's.
• Anifcanhave zerotomanyelsif'sand theymustcomebefore theelse.
• Onceanelsifsucceeds,noneoftheremainingelsif'sorelse'swillbetested.
Syntax
Thesyntaxofanif...elsif...elsestatementinPerlprogramminglanguageis−if(boolean_expre
ssion1){
#Executes whenthebooleanexpression 1 istrue
} elsif( boolean_expression 2) {
#Executes whenthebooleanexpression 2 istrue
} elsif( boolean_expression 3) {
#Executeswhen the boolean expression3istrue
}else{
#Executes when thenone ofthe above conditionistrue
}
#!/usr/local/bin/perl
$a=100;
# check the boolean condition using if
statementif($a==20){
# if condition is true then print the
followingprintf"a hasavaluewhichis 20\n";
}elsif($a==30 ){
# if condition is true then print the
followingprintf"a hasavaluewhichis 30\n";
}else{
#ifnone oftheabove conditionsistrue
49
printf"ahasavaluewhich is$a\n";
}
o/p:ahas a value which is100
Loops
Perl programming language provides the following types of loop to handle the
loopingrequirements.
AwhileloopstatementinPerlprogramminglanguagerepeatedlyexecutesatargetstatement
aslongasagivenconditionis true.
Syntax
The syntax of a while loop in Perl programming language is
−while(condition) {
statement(s);
}
#!/usr/local/bin/perl
$a=10;
# while loop
executionwhile($a<20
){
printf"Valueof a: $a\n";
$a=$a+1;
}
Hereweareusingthecomparisonoperator<tocomparevalueofvariable$aagainst
20. So while value of $a is less than 20, while loop continues executing a block
ofcode next to it and as soon as the value of $a becomes equal to 20, it comes out.
Whenexecuted,abovecodeproduces thefollowingresult −
Value of a:
10Value of a:
11Value of a:
12Value of a:
13Value of a:
14Value of a:
15Value of a:
16Value of a:
17Value of a:
18Valueofa:1
9
AnuntilloopstatementinPerlprogramminglanguagerepeatedlyexecutesatargetstatement
aslongasagivenconditionis false.
Syntax
The syntax of an until loop in Perl programming language is
−until(condition) {
50
statement(s);
}
#!/usr/local/bin/perl
$a=5;
# until loop
executionuntil( $a>10
){
printf"Valueofa: $a\n";
$a=$a+1;
}
Hereweareusingthecomparisonoperator>tocomparevalueofvariable$aagainst
10. So until the value of $a is less than 10, until loop continues executing a block
ofcode next to it and as soon as the value of $a becomes greater than 10, it comes
out.Whenexecuted,abovecodeproducesthefollowingresult−
Value of a:
5Value of a:
6Value of a:
7Value of a:
8Value of a:
9Valueofa:10
Aforloopisarepetitioncontrolstructurethatallowsyoutoefficientlywritealoopthat
needstoexecuteaspecificnumberoftimes.
Syntax
ThesyntaxofaforloopinPerlprogramminglanguageis−for(init;c
ondition; increment){
statement(s);
}
#!/usr/local/bin/perl
#forloopexecution
for( $a = 10; $a < 20; $a = $a + 1 )
{print"valueofa:$a\n";
}
Whentheabove codeisexecuted,itproducesthe
followingresult−valueofa:10
valueofa:11
value of a:
12value of a:
13value of a:
14value of a:
15value of a:
16valueofa:1
7
51
value of a:
18valueofa:1
9
Unlikeforandwhileloops,whichtesttheloopconditionatthetopoftheloop,the
do...while loopchecksitsconditionatthebottomof theloop.
A do...whileloopis similartoawhile loop,exceptthatado...while loopis guaranteedto
executeatleastonetime.
Syntax
The syntax of a do...while loop in Perl is
−do {
statement(s);
}while( condition
);#!/usr/local/bin/pe
rl
$a=10;
# do...while loop
executiondo{
printf"Valueofa: $a\n";
$a=$a+1;
}while($a<20 );
Whentheabove codeisexecuted,itproducesthe
followingresult−Valueofa:10
Value of a:
11Value of a:
12Value of a:
13Value of a:
14Value of a:
15Value of a:
16Value of a:
17Value of a:
18valueof
a:19
52
Arrays
An array is a variable that stores an ordered list of scalar values. Array variables
arepreceded by an "at" (@) sign. To refer to a single element of an array, you will use
thedollar sign ($) with the variable name followed by the index of the element in
squarebrackets.
Here is a simple example of using the array variables
−#!/usr/bin/perl
@ages =(25,30,40);
@names = ("John Paul", "Lisa",
"Kumar");print "\$ages[0]=$ages[0]\n";
print"\$ages[1]=$ages[1]\n";print"
\$ages[2]=$ages[2]\n";print
"\$names[0] = $names[0]\n";print
"\$names[1] =
$names[1]\n";print"\$names[2]=$
names[2]\n";
Here we have used the escape sign (\) before the $ sign just to print it. Other Perl
willunderstand it as a variable and will print its value. When executed, this will
producethe followingresult−
$ages[0]=25
$ages[1]=30
$ages[2]=40
$names[0] =JohnPaul
$names[1]=Lisa
$names[2]=Kumar
InPerl,ListandArray termsare oftenused asifthey'reinterchangeable.Butthelististhe
data,andthearrayis thevariable.
ArrayCreation
Arrayvariablesareprefixedwiththe@signandarepopulatedusingeitherparenthesesortheq
w operator.Forexample −
@array=(1,2,'Hello');@array=
qw/Thisisanarray/;
The second line uses the qw// operator, which returns a list of strings, separating
thedelimited string by white space. In this example, this leads to a four-element array;
thefirst element is 'this' and last (fourth) is 'array'. This means that you can use
differentlines asfollows−
@days =
qw/MondayTuesday
...
Sunday/;
53
AccessingArrayElements
Whenaccessingindividualelementsfromanarray,youmustprefixthevariablewitha dollar
sign ($) and then append the elementindex within the square brackets afterthe
nameofthe variable.Forexample −
#!/usr/bin/perl
@days=qw/MonTueWedThuFriSatSun/;print
"$days[0]\n";
print
"$days[1]\n";print
"$days[2]\n";print
"$days[6]\n";print"
$days[-1]\n";
print"$days[-7]\n";
This will produce the following result
−Mon
Tue
Wed
Sun
Sun
Mon
Array indices start from zero, so to access the first element you need to give 0
asindices. You can also give a negative index, in which case you select the element
fromthe end,ratherthan thebeginning,ofthearray.This meansthe following−
print $days[-1]; # outputs
Sunprint $days[-7]; # outputs
MonSequentialNumber
Arrays
Perloffersashortcutforsequentialnumbersandletters.Ratherthantypingouteach
element when counting to 100 for example, we can do something like as follows
−#!/usr/bin/perl
@var_10 =(1..10);
@var_20 =(10..20);
@var_abc =(a..z);
print"@var_10\n"; # Prints number from 1 to
10print"@var_20\n"; # Prints number from 10 to
20print"@var_abc\n";# Prints numberfromato z
Here double dot (..) is called range operator. This will produce the following result
−1 2345678910
10 11 12 13 1415 16 17 1819 20
abcdefghijklmn opqrst uvwxyz
54
Hashes
A hash is a set of key/value pairs. Hash variables are preceded by a percent (%)
sign.To refer to a single element of a hash,you will use the hash variable name
precededbya "$"signand followed bythe"key"associated withthevalue incurlybrackets..
Here is a simple example of using the hash variables
−#!/usr/bin/perl
%data=('JohnPaul',45,'Lisa',30,'Kumar',40);
print "\$data{'John Paul'} = $data{'John
Paul'}\n";print "\$data{'Lisa'}=$data{'Lisa'}\n";
print "\$data{'Kumar'} =
$data{'Kumar'}\n";This will producethe
followingresult −
$data{'JohnPaul'} =45
$data{'Lisa'}=30
$data{'Kumar'}=40
CreatingHashes
Hashesarecreatedinoneofthetwofollowingways.Inthefirstmethod,youassignavaluetoana
medkeyon aone-by-onebasis −
$data{'JohnPaul'} =45;
$data{'Lisa'}=30;
$data{'Kumar'}=40;
In the second case, you use a list, which is converted by taking individual pairs
fromthelist:thefirstelementofthepairisusedasthekey,andthesecond,asthevalue.For
example−
%data=('JohnPaul',45,'Lisa',30,'Kumar',40);
Forclarity,youcan use=>as an alias for,toindicate thekey/valuepairs as follows−
%data=('JohnPaul'=>45,'Lisa'=>30,'Kumar'=>40);
Here is one more variant of the above form, have a look at it, here all the keys
havebeenprecededbyhyphen(-)andnoquotation isrequiredaroundthem−
%data=(-JohnPaul=>45,-Lisa=>30,-Kumar=>40);
But it is important to note that there is a single word, i.e., without spaces keys
havebeen used in this form of hash formation and if you build-up your hash this way
thenkeyswillbeaccessedusinghyphenonly asshownbelow.
$val=%data{-JohnPaul}
$val=%data{-Lisa}
AccessingHashElements
When accessing individual elements from a hash, you must prefix the variable with
adollarsign($)andthenappendtheelementkeywithincurlybracketsafterthenameofthevaria
ble.Forexample −
#!/usr/bin/perl
%data=('JohnPaul'=>45,'Lisa'=>30,'Kumar'=>40);
55
print "$data{'John
Paul'}\n";print"$data{'Lisa'}
\n";
print"$data{'Kumar'}\n";
This will produce the following result
−45
30
40
ExtractingSlices
You can extract slices of a hash just as you can extract slices from an array. You
willneed to use @ prefix for the variable to store the returned value because they will
be alist ofvalues−
#!/uer/bin/perl
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar =>
40);@array=@data{-JohnPaul,-Lisa};
print"Array :@array\n";
This will produce the following result
−Array:4530
ExtractingKeysandValues
Youcangetalistofallofthekeysfromahashbyusingkeysfunction,whichhasthefollowingsy
ntax−
keys%HASH
Thisfunctionreturnsanarrayofallthekeysofthenamedhash.Followingistheexample−
#!/usr/bin/perl
%data=('JohnPaul'=>45,'Lisa'=>30,'Kumar'=>40);@names=ke
ys%data;
print
"$names[0]\n";print
"$names[1]\n";print
"$names[2]\n";
This will produce the following result
−Lisa
John
PaulKum
ar
GettingHashSize
You can get the size - that is, the number of elements from a hash by using the
scalarcontext on either keys or values. Simply saying first you have to get an array of
eitherthe keysorvalues andthen you cangetthe sizeofarrayasfollows −
#!/usr/bin/perl
%data=('JohnPaul'=>45,'Lisa'=>30,
'Kumar'=>40);@keys=keys%data;
56
$size=@keys;
print "1 - Hash size:is
$size\n";@values =values%data;
$size=@values;
print "2-Hash size:is $size\n";
This will produce the following result
−1-Hashsize:is3
2-Hashsize:is3
AddandRemoveElementsinHashes
Addinganewkey/valuepaircanbedonewithonelineofcodeusingsimpleassignment
operator. But to remove an element from the hash you need to use deletefunction
asshownbelowin theexample−
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' =>
40);@keys=keys%data;
$size=@keys;
print "1 - Hash size:is
$size\n";#addingan elementtothe
hash;
$data{'Ali'} =
55;@keys=keys%data;
$size=@keys;
print "2-Hash size:is $size\n";
#deletethesameelementfromthehash;delete
$data{'Ali'};
@keys= keys%data;
$size=@keys;
print "3-Hash size:is $size\n";
This will produce the following result
−1-Hashsize:is3
2 - Hashsize:is4
3 - Hashsize:is3
57
Strings
Strings are an essential part of the Perl language. They are scalar variables, so
theystartwith($)sign.Astringcanbedefinedwithinasinglequote(')ordoublequote(").
PerlStringOperators
The operators make it easy to manipulate a string in different ways. There are
twotypes ofstringoperators:
• Concatenation (.)
• Repetition(x)
ConcatenationOperator
Perlstringsareconcatenatedwitha(.)signinstead of(+)sign.
1. $firstName ="Christian";
2. $lastName ="Grey";
3. $fullName =$firstName ." ".$lastName;
4. print
"$fullName\n";Christian
Grey
RepeititionOperator
Perlstringscanbe repeatedanumberof timeswith(x) variable.
1. $text ="ThankYou ";
2. $output =$textx3;
3. print
"$output\n";Output:
ThankYouThankYouThankYou
InitializingandDeclaringaString
In Perl, to declare a string use my keyword before variable
name.Astringcanbe initialisedand
declaredwiththefollowingsyntax:
my$variableName ="";
Inthisexample,wehaveshownhowtoinitializeanddeclareastring.Wehaveprintedseveralst
ringstogetherbyusingadot(.)operator.
sestrict;
usewarnings;
#Declaringandinitializinga string.
my $msg1 = "Welcome at
JavaTpoint.";my $msg2 = "This is our
Perl Tutorial.";#printingusing.operator.
print $msg1 . "" . $msg2.
"\n";#print as separate
arguments.print$msg1,"",$ms
g2,"\n";
58
#embedd string in a bigger
string.print"$msg1$msg2\n";
Output:
Welcome at JavaTpoint. This is our Perl
Tutorial.Welcome at JavaTpoint. This is our Perl
Tutorial.Welcome at JavaTpoint. This is our Perl
Tutorial.DeterminingString Length,length()
stringlengthcan bedeterminedwithlength()function.
my $msg = "Our site javaTpoint provides all type of
tutorials";print"StringLength:",length($msg),"\n";
Output:
StringLength:50
Replacingastringwithanotherstring,s///g
Astringcanbereplacedwith anotherstringin twoways.
In first one, we have replaced Tigers with Lions which occurs single time in the
stringwiths///.
Insecondone, wehavereplacedroseswithflowersgloballywiths///g.
my$var1="Tigers arebigandfrightening.";
$var1 =~
s/Tigers/Lions/;print"$va
r1\n";
my$var2="Red roses are very popular.Yellow roses are less seen.";
$var2 =~
s/roses/flowers/g;print"$va
r2\n";
Output:
Lionsare bigand frightening.
Redflowers are very popular.Yellow flowers are lessseen.
PerlConcatenatingtwoStrings(.=)
Two strings can be joined together using (.=)
operator.my$str1="Wherethereisawill,";
my $str2 = "there is a
way.\n";my$joining='';
$joining=$str1 .'';
$joining .=
$str2;print
$joining;
Output:
Where thereis awill,thereis away.
59
Lists
A list is a collection of scalar values. We can access the elements of a list
usingindexes. Index starts with 0 (0th index refers to the first element of the list). We
useparenthesis and comma operators to construct a list. In Perl, scalar variables start
witha$ symbolwhereaslistvariablesstartwith @symbol.
Example:
#!/usr/bin/perl
# Empty List assigned to an
array@empty_list =();
# List
ofintegers@integer_list=(1,
2,3);
# List of strings assigned to an
array@string_list = ("hai", "for",
"hai");print "Empty list:
@empty_list\n";print "Integer list:
@integer_list\n";print "String list:
@string_list\n";Output:
Emptylist:
Integerlist: 1 2
3String list: hai for
haiBuiltinfunctions
Thechr()functioninPerlreturnsastringrepresentingacharacterwhoseUnicodecodepointis
aninteger.
join()function
join()functionisusedtocombinetheelementsofaListintoasinglestringwiththeuseofasepara
torprovided toseparateeachelement.
#!/usr/bin/perl
# Initializing list with alphabets A to
Z@list =(A..Z);
# Printing the original
listprint"List: @list\n";
# Using join function
introducing#hyphenbetweeneach
alphabets
print "\nString after join
operation:\n";print join("-",@list);
Output:
List:AB C DE F GHIJ K LMN O PQRS T U VWX YZ
60
Stringafterjoinoperation:
A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z
reverse()function
Reverse() function in Perl returns the elements of List in reverse order in a list
context.# Initializingalist
@list=("Raj","E123",12000);
# Reversing the
list@rname =
reverse(@list);#Printingth
ereversedlist
print "Reversed list is
@rname";# Initializingascalar
$string="for";
#Reversingascalar
$r=reverse($string);
print "\nReversed string is
$r";Reversed list is 12000 E123
RajReversed stringis rof
RegularExpressions
Aregularexpressionisastringofcharactersthatdefinesthepatternorpatternsyouareviewing.
Thereare three regular expression operators withinPerl.
• MatchRegularExpression -m//
• SubstituteRegularExpression-s///
• TransliterateRegularExpression -tr///
1. TheMatchOperator
The match operator, m//, is used to match a string or statement to a regular
expression.For example, to match the character sequence "foo" against the scalar $bar,
you mightuseastatementlikethis−
#!/usr/bin/perl
$bar = "This is foo and again
foo";if ($bar=~ /foo/) {
print"Firsttimeismatching\n";
}else{
print"Firsttimeisnotmatching\n";
}
$bar ="foo";
if($bar =~/foo/){
print"Secondtimeismatching\n";
}else{
61
print"Secondtimeisnotmatching\n";
}
When above program is executed, it produces the following result
−First timeismatching
Secondtimeismatching
2. TheSubstitutionOperator
The substitution operator, s///, is really just an extension of the match operator
thatallows you to replace the text matched with some new text. The basic form of
theoperatoris−
s/PATTERN/REPLACEMENT/;
#/user/bin/perl
$string="Thecat sat onthemat";
$string =~
s/cat/dog/;print
"$string\n";
When above program is executed, it produces the following result
−Thedogsatonthemat
3. TheTranslationOperator
Translationissimilar,butnotidentical,totheprinciplesofsubstitution,butunlikesubstitution
,translation(ortransliteration)doesnotuseregularexpressionsforitssearchon
replacementvalues.Thetranslation
operatorsare−tr/SEARCHLIST/REPLACEMENTLIST/cdsy/SEARCHLIST/REPLAC
EMENTLIST/cds
#/user/bin/perl
$string='Thecat satonthemat';
$string =~
tr/a/o/;print"$stri
ng\n";
When above program is executed, it produces the following result
−Thecotsotonthemot.
62
UNIT-IV
ApplicationsofPHP
Asmentionedbefore,PHPisoneofthemostwidelyusedlanguageovertheweb.I'mgoingtolist
fewofthemhere:
• PHPperformssystemfunctions,i.e.fromfilesonasystemitcancreate,open,read,write,
andclosethem.
• PHPcanhandleforms,i.e.gatherdatafromfiles,savedatatoafile,throughemail
youcansenddata,returndatatotheuser.
• Youadd,delete,modifyelementswithinyourdatabasethroughPHP.
• Accesscookiesvariablesandsetcookies.
• UsingPHP,youcan restrictusers toaccesssome pagesof yourwebsite.
63
• Itcanencryptdata.
Variables
Variablesare "containers"forstoringinformation.
Creating(Declaring)PHPVariables
InPHP, avariablestartswiththe$sign, followedbythenameofthevariable:
Example
<?php
$txt="Helloworld!";
$x=5;
$y=10.5;
?>
output:
Hey
Helloworld!
5
10.5
DataTypes
Variablescanstoredataofdifferenttypes,anddifferentdatatypescandodifferentthings.
PHPsupportsthefollowingdata types:
• String
• Integer
• Float(floatingpointnumbers- alsocalled double)
• Boolean
String
Astringisa sequenceofcharacters,like"Helloworld!".
Astringcan beany text insidequotes.Youcanuse single or double quotes:
<?php
$x="Helloworld!";
$y='Helloworld!';
echo$x;echo"<br>
";echo$y;
?>
Helloworld!
Hello
world!Integ
er
Anintegerdatatypeisanon-decimalnumberbetween-2,147,483,648and
2,147,483,647.
64
Rulesforintegers:
• Anintegermusthaveatleastonedigit
• Anintegermustnothaveadecimalpoint
• Anintegercanbeeitherpositiveornegative
• Integerscanbespecifiedin:decimal(base10),hexadecimal(base16),octal(base8),or
binary(base2)notation
Inthefollowingexample$xisaninteger.ThePHPvar_dump()functionreturnsthedatatypea
ndvalue:
<?php
$x=5985;
var_dump($x);
?>
int(5985)
Float
Afloat(floatingpointnumber)isanumberwithadecimalpointoranumberinexponential
form.
Inthefollowingexample$xisafloat.ThePHPvar_dump()functionreturnsthedatatype
andvalue:
Example
<?php
$x=10.365;
var_dump($x);
?>
float(10.365)
Boolean
ABooleanrepresentstwopossiblestates:TRUEor FALSE.
$x=true;
$y=false;
Operators
4+5 is equal to9.Here4and5arecalled operandsand+iscalledoperator.
ArithmeticOperators
65
ComparisonOperators
66
LogicalOperators
AssignmentOperators
67
ConditionalOperator
Thereisonemoreoperatorcalledconditionaloperator.Thisfirstevaluatesanexpressionforat
rueorfalsevalueandthenexecuteoneofthetwogivenstatements
dependingupontheresultof theevaluation.
Conditional
statementsTheIf...Else
Statement
Ifyouwanttoexecutesomecodeifaconditionistrueandanothercode ifaconditionis
false,usetheif. ......... elsestatement.
Syntax
if(condition)
code to be executed if condition is
true;else
codeto be executedifconditionis false;
Thefollowingexamplewilloutput"Haveaniceweekend!"ifthecurrentdayisFriday,Otherw
ise,it willoutput "Haveaniceday!":
<html>
<body>
<?php
$d=date("D");
if($d =="Fri")
echo"Haveaniceweekend!";else
echo"Haveaniceday!";
?>
</body>
</html>
It will produce the following result
−Haveaniceweekend!
ElseIfStatement
Ifyouwanttoexecutesomecodeifoneoftheseveralconditionsaretrueusetheelseifstatement
68
Syntax
if(condition)
code to be executed if condition is
true;elseif(condition)
code to be executed if condition is
true;else
codeto be executedifconditionis false;
Example
The following example will output "Have a nice weekend!" if the current day
isFriday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise, it
willoutput "Haveaniceday!"
<html>
<body>
<?php
$d=date("D");
if($d =="Fri")
echo"Haveaniceweekend!";else
if($d=="Sun")
echo"HaveaniceSunday!";else
echo"Haveaniceday!";
?>
</body>
</html>
It will produce the following result
−o/p:HaveaniceWeekend!
69
Loops
Loops in PHP areusedtoexecutethe sameblockofcodeaspecifiednumberoftimes.PHP
supportsfollowingfourlooptypes.
• for−loopsthroughablockofcodeaspecifiednumberoftimes.
• while−loopsthroughablockofcodeifandaslongasaspecifiedconditionistrue.
• do...while−loopsthroughablockofcodeonce,andthenrepeatstheloopaslongasaspec
ialconditionistrue.
• foreach −loopsthrough ablockof code for eachelementinan array.
forloop
Theforstatementisusedwhenyouknowhowmanytimesyouwanttoexecuteastatement
orablockofstatements.
Syntax
for (initialization; condition;
increment){codetobeexecuted;
}
whileloop
Syntax
while
(condition){codetob
eexecuted;
}
do-whileloop
do {
codeto be executed;
}
while
(condition);forea
ch
foreach (array as value)
{codeto beexecuted;
}
Arrays
arrayisan orderedmap(containsvalueonthebasisof
key).Itisusedtoholdmultiplevaluesofsimilartypeinasinglevariable.
IndexedArray
index is represented by number which starts from 0. We can store number, string
andobject in the PHP array. All PHP array elements are assigned to an index number
bydefault.
todefine indexed array:
$season=array("summer","winter","spring","autumn");
70
AssociativeArray
Wecanassociate namewitheach arrayelementsinPHPusing=>symbol.to
defineassociativearray:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
StringFunctions
71
Functions
functionisapieceofcodethatcanbereusedmanytimes.Itcantakeinputasargumentlist
andreturnvalue.Thereare thousands ofbuilt-in functions in PHP.
User-definedFunctions
Wecandeclareandcalluser-definedfunctionseasily.Let'sseethesyntaxtodeclareuser-
definedfunctions.
Syntax
1. function
functionname()2.{
3.//codetobeexecuted4.
}
<?php
functionsayHello(){
echo"HelloPHPFunction";
}
sayHello();//callingfunction
?>
o/p:HelloPHPFunction
Callbyvalue
Incallbyvalue,actualvalueisnotmodifiedifitismodifiedinsidethefunction.
<?php
functionincrement($i)
{
$i++;
}
$i=
10;increment(
$i);echo$i;
?>
o/p:10
CallByReference
Valuepassed tothefunctiondoesn'tmodifythe actualvalue bydefault (callbyvalue).But
wecandoso bypassingvalueasareference.
Bydefault,valuepassedtothefunctioniscallbyvalue.Topassvalueasareference,you needto
useampersand(&)symbol beforetheargument name.
<?php
functionadder(&$str2)
{
$str2.='CallBy Reference';
72
}
$str='Hello';a
dder($str);ech
o$str;
?>
HelloCallByReference
ParameterizedFunction
PHP Parameterized functions are the functions with parameters. You can pass
anynumber of parameters inside a function. These passed parameters act as
variablesinside yourfunction.
Theyare specifiedinsidetheparentheses,afterthefunction name.
Theoutputdependsuponthedynamicvaluespassedastheparametersintothefunction.
<!DOCTYPE html>
<html>
<head>
<title>Parameter AdditionandSubtractionExample</title>
</head>
<body>
<?php
//Addingtwonumbersfun
ction add($x,$y){
$sum=$x+$y;
echo"Sumoftwonumbersis=$sum<br><br>";
}
add(467,943);
//Subtracting two
numbersfunctionsub($x,
$y){
$diff=$x-$y;
echo"Difference betweentwonumbersis=$diff";
}
sub(943,467);
?>
</body>
</html>
73
FileHandling
PHPFileSystemallowsustocreatefile,readfilelinebyline,readfilecharacterbycharacter,wr
itefile,appendfile,delete fileand closefile.
OpenFile -fopen()
fopen() functionisusedtoopena file.
Syntax
resource fopen( string $filename , string $mode [, bool $use_include_path =
false[,resource$context
<?php
$handle=fopen("c:\\folder\\file.txt","r");
?>
CloseFile- fclose()
fclose() functionisusedtoclosean openfilepointer.
Syntax
oolfclose( resource $handle
)Example
<?phpfclose($h
andle);
?>
ReadFile- fread()
ThePHPfread()functionisusedtoreadthecontentofthefile.Itacceptstwoarguments:resourc
eandfilesize.
Syntax
stringfread( resource$handle,int$length)
<?php
$filename="c:\\myfile.txt";
$handle=fopen($filename,"r");//open fileinreadmode
$contents=fread($handle,filesize($filename));//readfile
WriteFile-fwrite()
fwrite()functionisusedtowritecontentof the
stringintofileSyntax
74
int fwrite( resource $handle , string $string [, int $length ]
)Example
<?php
$fp=fopen('data.txt','w');//openfileinwritemodefwri
te($fp,'hello');
fwrite($fp, 'php
file');fclose($fp);
echo"Filewrittensuccessfully";
?>
Output
Filewrittensuccessfully
FormHandling
WecancreateanduseformsinPHP.Togetformdata,weneedtousePHPsuperglobals
$_GETand$_POST.
The form requestmay beget or post.Toretrievedata fromgetrequest,we need touse
$_GET,forpostrequest$_POST.
GetForm
Get request is the default form request. The data passed through get request is
visibleon the URL browser so it is not secured. You can send limited amount of data
throughget request.
<form action="welcome.php"
method="get">Name:<inputtype="text"na
me="name"/>
<inputtype="submit"value="visit"/>
</form>
<?php
$name=$_GET["name"];//receivingnamefieldvaluein$namevariableech
o"Welcome,$name";
?>
PostForm
Postrequestiswidelyusedtosubmitformthathavelargeamountofdatasuchasfileupload,ima
geupload,login form,registration formetc.
ThedatapassedthroughpostrequestisnotvisibleontheURLbrowsersoitissecured.Youcan
sendlarge amountof datathroughpost request.
<formaction="login.php" method="post">
<table>
<tr><td>Name:</td><td><inputtype="text"name="name"/></td></tr>
<tr><td>Password:</td><td><inputtype="password"name="password"/></td
></tr>
75
<tr><tdcolspan="2"><inputtype="submit" value="login"/></td></tr>
</table>
</form>
<?php
$name=$_POST["name"];//receivingnamefieldvaluein$namevariable
$password=$_POST["password"];//receiving password field value in
$passwordvariable
echo"Welcome:$name,yourpasswordis:$password";
?>
76
UNIT-V
Rubyisaobject-oriented,reflective,general-purpose,dynamicprogramminglanguage.
Ruby was developed to make it act as a sensible buffer between humanprogrammers
and the underlying computing machinery. It is an interpreted scriptinglanguage which
means most of its implementations execute instructions directly andfreely, without
previously compiling a program into machine-language
instructions.Rubyisusedtocreatewebapplicationsofdifferentsorts.Itisoneofthehottechnol
ogyatpresenttocreatewebapplications.
Datatypes
Data types represents a type of data such as text, string, numbers, etc. There
aredifferentdatatypesinRuby:
• Numbers
• Strings
• Symbols
• Hashes
• Arrays
Numbers
Integersandfloatingpointnumbers comeinthecategoryofnumbers.
Integers are held internally in binary form. Integer numbers are numbers without
afraction. According to their size, there are two types of integers. One is Bignum
andotherisFixnum.
Strings
Astringisagroupof letters that represent asentence or aword.Stringsaredefined
byenclosingatext withinsingle(')ordouble(") quote.
Symbols
Symbolsarelikestrings. Asymbolisprecededbyacolon(:). Forexample,
1.:abcd
They do not contain spaces. Symbols containing multiple words are written with
(_).One difference between string and symbol is that, if text is a data then it is a string
butif itisacodeitisasymbol.
Symbolsareuniqueidentifiersand representstaticvalues,whilestring
representvaluesthatchange.
Hashes
A hash assign its values to its keys. They can be looked up by their keys. Value to
akey is assigned by =>sign. A key/value pair is separated with a comma between
themandallthe pairsareenclosedwithin curlybraces.Forexample,
• {"Akash"=>"Physics","Ankit"=>"Chemistry","Aman"=>"Maths"}
77
Arrays
An array stroes data or list of data. It can contain all types of data. Data in an array
areseparatedbycommainbetweenthemandareenclosedbysquarebracket.Forexample,
1.["Akash","Ankit", "Aman"]
Variables
Variables are the memory locations, which hold any data to be used by any
program.Localvariablesbeginwith a lowercaseletter or _.The scope ofa local
variablerangesfromclass,module,def,ordotothecorrespondingendorfromablock'sopenin
gbracetoitsclosebrace{}.Whenanuninitializedlocalvariableisreferenced,itisinterpreteda
sacalltoamethodthathasnoarguments.Globalvariablesbeginwith$.Uninitializedglobalva
riableshavethevaluenilandproducewarningswiththe-
woption.Assignmenttoglobalvariablesalterstheglobalstatus.Itisnotrecommendedto
useglobal variables.Theymakeprogramscryptic.
Operators
Ruby supports a rich set of operators, as you'd expect from a modern language.
Mostoperators are actually method calls. For example, a + b is interpreted as a.+(b),
wherethe+methodintheobject referredtobyvariable a iscalled withbas itsargument.
ArithmeticOperators
78
ComparisonOperators
AssignmentOperators
79
BitwiseOperators
LogicalOperators
80
TernaryOperator
Itfirstevaluatesanexpressionforatrueorfalsevalueandthenexecutesoneofthetwo given
statementsdependingupontheresultof theevaluation.
Conditionalstatements
Rubyoffersconditionalstructuresthatareprettycommontomodernlanguages.
Rubyif...elseStatement
Syntax
if conditional
[then]code...
[elsif conditional
[then]code...]...
[else
code...]
end
#!/usr/bin/ruby
x =1
if x>2
puts "x is greater than
2"elsifx <=2 andx!=0
puts "x is
1"else
puts"Ican't guessthenumber"end
x is1
RubyunlessStatement
Syntax
unless conditional
[then]code
[else
code]
81
end
Executescodeifconditionalisfalse.Iftheconditionalistrue,codespecifiedintheelseclauseis
executed.
#!/usr/bin/ruby
x =1
unlessx>=2
puts "x is less than
2"else
puts "x is greater than
2"end
This will produce the following result
−x islessthan2
Loops
LoopsinRubyareusedtoexecutethesameblockofcodeaspecifiednumberoftimes.
RubywhileStatement
Syntax
while conditional
[do]code
end
#!/usr/bin/ruby
$i =0
$num=5
while$i<$numdoputs("Insidethe
loopi=#$i")
$i+=1
end
This will produce the following result
−Inside theloopi =0
Inside the loop i =
1Inside the loop i =
2Inside the loop i =
3Insidetheloopi=4
for
statementSyntax
for variable [, variable ...] in expression
[do]code
end
82
#!/usr/bin/ruby
fori in 0..5
puts "Value of local variable is
#{i}"end
Here,wehavedefinedtherange0..5.Thestatementforiin0..5willallowitotakevalues in the
range from 0 to 5 (including 5). This will produce the following result
−Valueoflocalvariableis0
Valueoflocal variableis1
Value of local variable is
2Value of local variable is
3Value of local variable is
4Value of local variable is
5Methods
Ruby methods are very similar to functions in any other programming language.
Rubymethodsareused to bundleoneor morerepeatable statements intoasingleunit.
def
method_namee
xpr..
end
#!/usr/bin/ruby
def test(a1="Ruby",a2="Perl")
puts"Theprogramminglanguageis#{a1}"pu
ts"Theprogramminglanguageis#{a2}"
end
test "C",
"C++"test
This will produce the following result
−Theprogramminglanguageis C
TheprogramminglanguageisC++
The programming language is
RubyThe programming language is
PerlreturnStatement
ThereturnstatementinrubyisusedtoreturnoneormorevaluesfromaRuby
Method.
deftest
i=100
j=200
k=300
return i, j,
kend
var=test
83
putsvar
This will produce the following result
−100
200
300
Blocks
Ablockconsists ofchunks ofcode.
• Youassignaname toablock.
• The code in theblockisalwaysenclosed within braces ({}).
• A block is always invoked from a function with the same name as that of
theblock. This means that if you have a block with the name test, then you use
thefunction testtoinvokethisblock.
• Youinvokea blockbyusingthe yieldstatement.
syntax
block_name{
statement1s
tatement2
..........
}
#!/usr/bin/ruby
deftest
puts"Youareinthemethod"yiel
d
puts"Youareagainbacktothemethod"yield
end
test{puts "Youare intheblock"}
This will produce the following result
−You arein themethod
Youareinthe block
YouareagainbacktothemethodYou
areintheblock
Modules
Modulesareawayofgroupingtogethermethods,classes,andconstants.Modulesgiveyoutw
omajorbenefits.
• Modulesprovideanamespaceandpreventnameclashes.
• Modulesimplementthemixinfacility.
Modulesdefineanamespace,asandboxinwhichyourmethodsandconstantscanplaywithout
havingtoworryaboutbeingstepped on byothermethodsand constants.
84
Syntax
module
Identifierstate
ment1statemen
t2
...........
end
Module constants are named just like class constants, with an initial uppercase
letter.The method definitions look similar, too: Module methods are defined just like
classmethods.
As with class methods, you call a module method by preceding its name with
themodule's name and a period, and you reference a constant using the module name
andtwo colons.
Example
#!/usr/bin/ruby
# Module defined in trig.rb
filemodule Trig
PI=3.141592654
def
Trig.sin(x)#..
end
def
Trig.cos(x)#..
end
end
Wecandefineonemoremodulewiththesamefunctionnamebutdifferentfunctionality
#!/usr/bin/ruby
# Module defined in moral.rb
filemodule Moral
VERY_BAD=0
BAD=1
def
Moral.sin(badness)#...
end
end
Likeclassmethods,wheneveryoudefineamethodinamodule,youspecifythemodule
namefollowedby adotandthenthe method name.
85
Arrays
Ruby arrays are ordered, integer-indexed collections of any object. Each element in
anarrayisassociatedwith andreferredto byanindex.
Array indexing starts at 0, as in C or Java. A negative index is assumed relative to
theend of the array --- that is, an index of -1 indicates the last element of the array, -2
isthe nexttolastelement inthearray,andsoon.
CreatingArrays
There are many ways to create or initialize an array. One way is with the new
classmethod−
names= Array.new
You can set the size of an array at the time of creating array
−names=Array.new(20)
The array names now has a size or length of 20
elements.#!/usr/bin/ruby
names=Array.new(20)
putsnames.size#Thisreturns 20
puts names.length # This also returns
20This will produce the following result
−20
20
You can assign a value to each element in the array as
follows#!/usr/bin/ruby
names = Array.new(4,
"mac")puts "#{names}"
This will produce the following result
−["mac","mac","mac","mac"]
Youcanalsouseablockwithnew,populatingeachelementwithwhattheblock
evaluates
to#!/usr/bin/ru
by
nums=Array.new(10){ |e|e=e * 2}
puts"#{nums}"
This will produce the following result
−[0,2,4,6,8,10,12,14,16,18]
There is another method of Array, []. It works like this
−nums =Array.[](1,2,3,4,5)
One more formof array creationisasfollows−
nums=Array[1,2,3, 4,5]
86
Strings
AStringobjectinRubyholdsandmanipulatesanarbitrarysequenceofoneormorebytes,typic
ally representingcharacters thatrepresent human language.
Thesimpleststringliteralsareenclosedinsinglequotes(theapostrophecharacter).Thetext
withinthe quote marksis the valueofthe string−
'ThisisasimpleRuby stringliteral'
ExpressionSubstitution
ExpressionsubstitutionisameansofembeddingthevalueofanyRubyexpressioninto
astringusing#{and}−
#!/usr/bin/ruby
x,y,z=12,36,72
puts"Thevalue of x is#{ x}."
puts "The sum of x and y is #{ x + y
}."puts "The average was #{ (x + y + z)/3
}."This will produce the following result
−Thevalueofx is12.
The sum of x and y is
48.The averagewas40.
WeneedtohaveaninstanceofStringobjecttocallaStringmethod.Followingisthewaytocreat
eaninstanceofStringobject−
new[String.new(str="")]
Thiswillreturna newstringobjectcontainingacopy
ofstr.Now,usingstrobject,wecanalluseanyavailableinstancemethods.
#!/usr/bin/ruby
myStr=
String.new("THISISTEST")foo=mySt
r.downcase
puts"#{foo}"
This will produce the following result
−this istest
Hashes
A Hash is a collection of key-value pairs like this: "employee" = > "salary". It
issimilar to an Array, except that indexing is done via arbitrary keys of any object
type,not anintegerindex.
The order in which you traverse a hash by either key or value may seem arbitrary
andwill generally not be in the insertion order. If you attempt to access a hash with a
keythat doesnotexist,themethodwillreturnnil.
87
CreatingHashes
Aswitharrays,thereisavarietyofwaystocreatehashes.Youcancreateanemptyhashwiththen
ewclassmethod −
months =
Hash.new#!/usr/bin
/ruby
months = Hash.new( "month"
)puts "#{months[0]}"
puts"#{months[72]}"
This will produce the following result
−month
month
#!/usr/bin/ruby
H=Hash["a"=>100,"b"=>200]
puts"#{H['a']}"
puts"#{H['b']}"
This will produce the following result
−100
200
FileI/O
RubyprovidesawholesetofI/O-relatedmethodsimplementedintheKernelmodule.All
theI/OmethodsarederivedfromtheclassIO.
TheclassIOprovidesallthebasicmethods,suchasread,write,gets,puts,readline,getc,andpri
ntf.
TheputsStatement
Inthepreviouschapters,youhaveassignedvaluestovariablesandthenprintedtheoutput
usingputsstatement.
Theputsstatementinstructstheprogramtodisplaythevaluestoredinthevariable.This
willaddanewlineatthe endofeachlineit writes.
#!/usr/bin/ruby
val1 = "This is variable
one"val2 = "This is variable
two"puts val1
putsval2
This will produce the following result
−This isvariableone
Thisisvariabletwo
ThegetsStatement
ThegetsstatementcanbeusedtotakeanyinputfromtheuserfromstandardscreencalledSTDI
N.
88
Example
The following code shows you how to use the gets statement. This code will
promptthe user to enter a value, which will be stored in a variable val and finally will
beprintedonSTDOUT.
#!/usr/bin/ruby
puts "Enter a value
:"val =gets
putsval
This will produce the following result
−Enteravalue:
Thisisenteredvalue
Thisisenteredvalue
TheputcStatement
Unliketheputsstatement,whichoutputstheentirestringontothescreen,theputcstatement
canbeusedto outputonecharacterat atime.
Example
The output of the following code is just the character H
−#!/usr/bin/ruby
str="HelloRuby!"
putc str
This will produce the following result
−H
TheprintStatement
The print statement is similar to the puts statement. The only difference is that the
putsstatement goes to the next line after printing the contents, whereas with the
printstatement thecursoris positionedonthe sameline.
#!/usr/bin/rubyprint
"HelloWorld"
print"GoodMorning"
This will produce the following result
−Hello WorldGoodMorning
OpeningandClosingFiles
Untilnow,youhavebeenreadingandwritingtothestandardinputandoutput.Now,wewillsee
howtoplaywithactualdatafiles.
The File.newMethod
YoucancreateaFileobjectusingFile.newmethodforreading,writing,orboth,accordingtoth
emodestring.Finally,youcanuseFile.closemethodtoclosethatfile.
Syntax
aFile=File.new("filename", "mode")
89
# ... process the
fileaFile.close
The File.openMethod
YoucanuseFile.openmethodtocreateanewfileobjectandassignthatfileobjecttoa file.
However, there is one difference in between File.open and File.new methods.The
difference is that the File.open method can be associated with a block, whereasyou
cannotdothesameusingtheFile.newmethod.
File.open("filename","mode")do|aFile|
# ... process the
fileend
HereisalistofTheDifferentModesofopeninga File−
ReadingandWritingFiles
The same methods that we've been using for 'simple' I/O are available for all
fileobjects. So, gets reads a line from standard input, and aFile.gets reads a line from
thefileobjectaFile.
The sysreadMethod
You can use the method sysread to read the contents of a file. You can open the file
inanyofthe modeswhenusingthemethod sysread.For example −
Followingistheinputtextfile−
This is a simple text file for testing
purpose.Nowlet's tryto readthis
file−#!/usr/bin/ruby
aFile = File.new("input.txt",
"r")if aFile
content=aFile.sysread(20)pu
tscontent
else
puts"Unabletoopenfile!"end
Thisstatementwilloutputthefirst20charactersofthefile.Thefilepointerwillnowbeplacedat
the21stcharacterinthe file.
ThesyswriteMethod
Youcanusethemethodsyswritetowritethecontentsintoafile.Youneedtoopenthefilein
writemode whenusingthe methodsyswrite.For example −
#!/usr/bin/ruby
aFile = File.new("input.txt",
"r+")if aFile
aFile.syswrite("ABCDEF")e
lse
puts"Unable toopen file!"
90
end
RenamingandDeletingFiles
YoucanrenameanddeletefilesprogrammaticallywithRubywiththerenameanddeletemeth
ods.
Following is the example to rename an existing file test1.txt
−#!/usr/bin/ruby
# Rename a file from test1.txt to
test2.txtFile.rename("test1.txt","test2.txt
")
Following is the example to delete an existing file test2.txt
−#!/usr/bin/ruby
# Deletefiletest2.txt
File.delete("test2.txt")
Form
HandlingForm
Tocreateaformtagwiththespecifiedaction,andwithPOSTrequest,usethefollowingsyntax
−
<%=form_tag:action =>'update',:id =>@some_object %>
<%=form_tag({:action=>:save,},{ :method=>:post})%>
Use:multipart=>true todefine a MIME-multipart form(for file uploads).
<%=form_tag({:action=>'upload'},:multipart=>true)%>
FileUpload
Defineamultipartforminyour view−
<%= form_tag( { :action => 'upload' }, :multipart => true )
%>Uploadfile:<%= file_field("form","file")%>
<br/>
<%=submit_tag("Uploadfile" )%>
<%=end_form_tag%>
Handletheuploadinthecontroller −
def upload
file_field=@params['form']['file']rescuenil
# file_field is a StringIO
objectfile_field.content_type#'tex
t/csv'file_field.full_original_filen
ame
...
end
91
TextFields
Tocreate a textfield usethefollowingsyntax−
<%=text_field:modelname, :attribute_name,options%>
Have a lookatthefollowingexample−
<%=text_field "person", "name","size"=>20%>
Thiswillgenerate followingcode −
<inputtype="text"id="person_name"name="person[name]"size=
"20"value="<%[email protected]%>" />
Tocreatehidden fields,usethefollowingsyntax;
<%=hidden_field...%>
Tocreatepassword fields,use thefollowingsyntax;
<%=password_field ... %>
Tocreate file upload fields,usethe followingsyntax;
<%=file_field ...%>
TextArea
Tocreate a textarea,use thefollowingsyntax−
<%=text_area...%>
Have a lookatthefollowingexample−
<%=text_area"post","body", "cols"=>20, "rows"=>40%>
Thiswillgenerate thefollowingcode−
<textareacols="20"rows="40"id="post_body" name="post[body]">
<%={@post.body}%>
</textarea>
RadioButton
Tocreate aRadioButton,use thefollowingsyntax−
<%=radio_button:modelname, :attribute, :tag_value, options%>
Havea lookatthefollowingexample−
radio_button("post","category","rails")r
adio_button("post","category","java")
Thiswillgenerate thefollowingcode−
<inputtype="radio" id="post_category"
name="post[category]"value="rails"checked= "checked"/>
<inputtype ="radio" id ="post_category"name="post[category]"value="java" />
CheckboxButton
Tocreatea CheckboxButtonusethefollowingsyntax−
<%=check_box:modelname,:attribute,options,on_value,off_value%>
Havea lookatthefollowingexample−
check_box("post","validated")
Thiswillgenerate thefollowingcode−
92
<inputtype="checkbox"id="post_validate"name="post[validated]"value
="1" checked="checked" />
<inputname ="post[validated]" type="hidden"value ="0"/>
Let'scheckanother example−
check_box("puppy","gooddog",{},"yes","no")
Thiswillgenerate followingcode −
<inputtype="checkbox"id="puppy_gooddog"name="puppy[gooddog]"value="yes" />
<inputname ="puppy[gooddog]"type="hidden"value ="no"/>
Options
Tocreate a dropdopwn list,usethefollowingsyntax−
<%=select:variable,:attribute,choices,options,html_options%>
Have a lookatthefollowingexample−
select("post", "person_id", Person.find(:all).collect{|p|[p.name,p.id]})
Thiscouldgeneratethefollowingcode.Itdependsonwhatvalueisavailableinyour
database. −
<selectname="post[person_id]">
<optionvalue="1">David</option>
<optionvalue="2">Sam</option>
<optionvalue="3">Tobias</option>
</select>
DateTime
Followingisthesyntaxtousedataandtime−
<%=date_select :variable,:attribute, options%>
<%=datetime_select:variable,:attribute,options%>
Followingareexamplesofusage−
<%=date_select"post","written_on"%>
<%=date_select"user","birthday", :start_year=>1910%>
<%=date_select"user","cc_date",:start_year=>2005,
:use_month_numbers=>true, :discard_day=>true, :order=>[:year, :month]%>
<%=datetime_select"post","written_on"%>
EndFormTag
Usefollowingsyntaxtocreate </form>tag−
<%=end_form_tag%>
93