PG - M.sc. - Information Technology - 31331 Open Source Software
PG - M.sc. - Information Technology - 31331 Open Source Software
(Accredited with ‘A+’ Grade by NAAC (with CGPA: 3.64) in the Third Cycle and Graded
as category - I University by MHRD-UGC)
(A State University Established by the Government of Tamilnadu)
All rights reserved. No part of this publication which is material protected by this copyright notice may be
reproduced or transmitted or utilized or stored in any form or by any means now known or hereinafter
invented, electronic, digital or mechanical, including photocopying, scanning, recording or by any information
storage or retrieval system, without prior written permission from the Alagappa University, Karaikudi, Tamil
Nadu.
Reviewer:
Dr. P. Prabhu
Assistant Professor in Information Technology
Directorate of Distance Education
Alagappa University,
Karaikudi.
SYLLABI-BOOK MAPPING TABLE
Open Source Software
SYLLABI MAPPING IN BOOK
BLOCK1: INTRODUCTION
( Pages 1-7)
UNIT-1:Introduction to Open Sources: Need of Open Sources-
Advantages of Open Sources-Applications of Open sources
(Pages 8-17)
UNIT-2:Open Source Operating System: LINUX: Introduction-
General Overview-Kernel Mode and user mode-Process
(Pages 18-30)
UNIT-3:Advanced Concepts: Scheduling-Personalities-Cloning-
Signals-Development with Linux
BLOCK 2: OPEN SOURCE DATABASE
(Pages 31-40)
UNIT-4:MySQL: Introduction -Setting up Account Starting,
terminating and writing your Own SQL programs
(Pages 41-55)
UNIT-5:Record selection Technology-Working with strings-Date
and Time
(Pages 56-66)
UNIT-6:Sorting query Results-Generating Summary-Working
with Metadata- Using Sequences- My SQL and Web
BLOCK 3: OPEN SOURCE PROGRAMMING LANGUAGE-
PHP
(Pages 67-82)
UNIT-7:PHP: Introduction- Programming in Web Environment-
Variables-Constants-Data types-Operators- Statements
UNIT-14: Packages and Modules- Working with Files- Data (Pages 222-235)
Manipulation
Structure
1.0 Introduction
1.1 Objective
1.2 Software Terminologies
1.2.1 Public Domain Software
1.2.2 Freeware
1.2.3 Shareware
1.2.4 Firmware
1.2.5 Proprietary Software
1.2.6 Open Source Software
1.3 Need of Open Sources
1.4 Advantages of Open Sources
1.5 Applications of Open sources
1.6 Answers to Check Your Progress
1.7 Summary
1.8 Keywords
1.9 Self Assessment Questions and Exercises
1.10 Further Readings
1.0 INTRODUCTION
This unit explains the open source software concepts and basics of the
system with which we work .The applications and need of this software and
how it is freely available is discussed.
1.1 OBJECTIVE
This unit briefs the open source software needs and makes the user to
understand and learn the following concepts
Need of open sources
Applications
Advantages
Self-Instructional Material
Introduction
1.2.1 Public Domain Software
Public domain software refers to any program that is not copy righted. This
software is free and can be used without restrictions, that is, the user can
copy, distribute, and even modify the software without obtaining permission
from the software developer.
NOTES
1.2.2 Freeware
The term freeware is commonly used for copyrighted software given away
free by its author. It is available for free but the author retains the copyright,
which means that a user does not have the right to modify anything in the
software that is not explicitly allowed by the developer. Thus, freeware
software permits re-distribution but not modification.
1.2.3 Shareware
Shareware is the software which comes with permission for people to
redistribute copies for a limited period. Anyone who continues to use a copy
is required to pay a license fee. Therefore, a free use of the software is
usually limited to a period. It is distributed without payment ahead of time.
1.2.4 Firmware
Firmware is a combination of software, permanently stored in the memory.
As the name suggests, firmware is a program or data that has been written
onto read only memory (ROM).
1. Free Redistribution
The license shall not restrict any party from selling or giving away the
software as a component of an aggregate software distribution containing
programs from several different sources. The license shall not require a
royalty or other fee for such sale
Self-Instructional Material
2. Source Code
Introduction
The program must include source code, and must allow distribution in source
code as well as compiled form. Where some form of a product is not
distributed with source code, there must be a well-publicized means of
obtaining the source code for no more than a reasonable reproduction cost
NOTES
preferably, downloading via the Internet without charge. The source code
must be the preferred form in which a programmer would modify the
program. Deliberately obfuscated source code is not allowed. Intermediate
forms such as the output of a preprocessor or translator are not allowed.
3. Derived Works
The license must allow modifications and derived works, and must allow
them to be distributed under the same terms as the license of the original
software.
Self-Instructional Material
9. License Must Not Restrict Other Software
Introduction
The license must not place restrictions on other software that is distributed
along with the licensed software. For example, the license must not insist
that all other programs distributed on the same medium must be open-source
software.
NOTES
10. License Must Be Technology-Neutral
No provision of the license may be predicated on any individual technology
or style of interface.
Self-Instructional Material
· Combats Piracy
Introduction
· Total Cost of Ownership
· Non Quantitative Issues
· Freedom from control by another
NOTES
· Protection from licensing litigation
· Flexibility
· Social/Moral/Ethical Issues
· Innovation
Self-Instructional Material
3. Firmware is a combination of software, permanently stored in the
Introduction memory. As the name suggests, firmware is a program or data that
has been written onto read only memory (ROM).
4. The name “FOSS” is a recursive acronym for “Free Open Source
Software”. Free software is a matter of the users’ freedom to run,
NOTES copy, distribute, study, change and improve the software.
5. Some of advantages are:
Reliability
Security
Combats Piracy
Total Cost of Ownership
Non-Quantitative Issues
Freedom from control by another
Protection from licensing litigation
Flexibility
Social/Moral/Ethical Issues
Innovation
1.7. SUMMARY
Firmware is a combination of software, permanently stored in the
memory. As the name suggests, firmware is a program or data that
has been written onto read only memory (ROM).
Proprietary describes a technology or product that is owned
exclusively by a single company that carefully guards knowledge
about the technology or the product’s internal working.
The program must include source code, and must allow distribution
in source code as well as compiled form.
The rights attached to the program must apply to all to whom the
program is redistributed without the need for execution of an
additional license by those parties.
1.8. KEYWORDS
FOSS: The name “FOSS” is a recursive acronym for “Free Open Source
Software”. Free software is a matter of the users’ freedom to run, copy,
distribute, study, change and improve the software.
Free software: Free software is software that gives you the user the freedom
to share study and modify it.
Free Redistribution: The license shall not restrict any party from selling or
giving away the software as a component of an aggregate software
distribution containing programs from several different sources.
Self-Instructional Material
Introduction
1.9. SELF ASSESSMENT QUESTIONS AND EXERCISES
Short Answer questions:
1. What is Distribution of License?
2. What is Shareware? NOTES
3. What is Proprietary Software?
4. What are the needs of open source?
5. What are applications of open source?
Self-Instructional Material
Open Source Operating
Systems UNIT- 2
OPEN SOURCE OPERATING SYSTEMS
NOTES Structure
2.0 Introduction
2.1 Objective
2.2 Open Source Operating System
2.3 General Overview
2.4 Kernel Mode
2.5 User Mode
2.6 Process
2.6.1 Creating Processes
2.6.2 Destroying Processes
2.6.3 Process Removal
2.7 Answers to Check Your Progress
2.8 Summary
2.9 Keywords
2.10 Self Assessment Questions and Exercises
2.11 Further Readings
2.0 INTRODUCTION
This unit briefs the open source operating system Linux with its general
overview of how its available and its usage and working mode are explained,
2.1OBJECTIVE
This unit helps the users to understand linx by
Linux
Linus Torvalds [Matt Welsh], a student at the University of Helsinki, created
the first version of “Linux” in August 1991. Released as an open-source
software under the Free Software Foundation's GNU General Public License
(GPL), Linux quickly grew into a complete operating-system package, with
contributions from hundreds of programmers. Since the release of version
1.0 in 1994, organizations have been able to download free copies of Linux.
One could also purchase commercial distributions of Linux from companies
8
Self-Instructional Material
such as Slackware, Red 3 Hat etc who also provide consultancy, services,
Open Source Operating
and maintenance [Carla Schroder]. Many people raise a question about Systems
Linux “if it's released under the Free Software Foundation's GPL, shouldn't it
be free?”. The answer is no. A company can charge money for products that
include Linux, as long as the source code is made available. The GPL allows
NOTES
people to distribute (and charge for) their own versions of free software
[Carla Schroder]. According to the Free Software Foundation, the "free" in
free software refers to freedom or liberty, not price. In the foundation's
definition, organizations have the freedom to run software for any purpose,
study how it works, modify, improve and re-release it.
Another common misconception about Linux is that it's a complete operating
system. In reality Linux refers to the “ kernel or core ” of the operating
system. Combining Linux with a set of open-source GNU programs from the
Free Software Foundation turns it into what most people know as Linux
”forming both the full operating system and the core of most Linux
distributions”. Distributions are the versions of Linux, GNU programs, and
other tools that are offered by different companies, organizations, or
individuals. Popular distributions include Red Hat, Debian, SuSE, Caldera,
and others. Each distribution might be based on a different version of the
Linux kernel, but all migrate forward over time, picking up core changes that
are made to the kernel and keeping everything in somewhat loose
synchronization.
Eric S. Raymond's famous essay, "The Cathedral and the Bazaar," argues
that most commercial software is built like cathedrals by small groups of
artisans working in isolation. Open-source software, like Linux, is developed
collectively over the Internet, which serves as an electronic bazaar for
innovative ideas. The first of the two programming styles is closed source –
the traditional factory-production model of proprietary software, in which
customers get a sealed block of computer binary that they cannot examine,
modify, or evolve. The other style is opensource, the Internet engineering
tradition in which software source code is generally available for inspection,
independent peer review, and rapid evolution. Linux operating environment
is the standard-bearer of the open source approach.
With Open Source products like Linux, new changes come through an open
development model, meaning that all new versions are available to the
public, regardless of their quality. "Linux' s versioning scheme is designed to
let users understand whether they're using a stable version or adevelopment
version," says Jim Enright, director of Oracle's Linux program office. "Even
decimal-numbered releases [such as 2.0, 2.2, and 2.4] are considered stable
versions, while odd numbered releases [such as 2.3 and 2.5] are beta-quality
releases intended for developers only." For much of the 1990s, Linux was
primarily an experiment: something that developers fiddled with and used on
local servers to see how well it worked and how secure it was. Then, with the
internet boom of the late 1990s, many companies started using Linux for
their Web servers, fueling the first wave of corporate Linux adoption leading
to over 30 percent penetration of web server market by 2002.
Self-Instructional Material
Open source movement today is no more about just Linux, there are
Open Source Operating hundreds of thousands of software products being worked on in the
Systems
Free/Open Source Software (FOSS) mode—Apache, MySQL, Postgres,
Firefox ,Jboss etc are some of the other popular members of this growing
family who have proved themselves in the real world. Also, its influence is
no more confined to CSE/IT areas alone; Open Source solutions are today
NOTES available for many of the simulation, computing, design and visualization
needs of the entire Scientific and Engineering community. It is for reasons
such as the above that most of the major global players in the computing
arena 4such as IBM, Intel, Oracle, HP etc all have started their own in-house
FOSS initiatives.
Self-Instructional Material
standard subroutines to find the code for these subroutines in the libraries at
Open Source Operating
runtime. This saves a large amount of space, as each application doesn't store Systems
its own copy of these common routines.
Linux Distributions
NOTES
Here are some of the more popular distributions of Linux.
* Mandrake
* Red Hat
* SuSE
* Caldera
* Corel
* Debian
* Slackware
* TurboLinux
* Ubuntu
11
Self-Instructional Material
Necessity of Dual Mode (User Mode and Kernel Mode) in Operating
Open Source Operating
System
Systems
The lack of a dual mode i.e user mode and kernel mode in an operating
system can cause serious problems. Some of these are: A running user
program can accidentally wipe out the operating system by overwriting it
with user data. Multiple processes can write in the same system at the same
NOTES
time, with disastrous results. These problems could have occurred in the MS-
DOS operating system which had no mode bit and so no dual mod
2.6 PROCESS
A process is usually defined as an instance of a program in execution; thus, if
16 users are running vi at once, there are 16 separate processes..
Process Descriptor
To manage processes, the kernel must know the process's priority, whether it
is running on the CPU or blocked on some event, what address space has
been assigned to it and so on. This is the role of the process descriptor, that
is, of a task_struct type
Process State
The following are the possible process states:
TASK_RUNNING The process is either executing on the CPU or waiting to
be executed.
TASK_INTERRUPTIBLE The process is suspended (sleeping) until some
condition becomes true.
TASK_UNINTERRUPTIBLE like previous state, except that delivering a
signal to the sleeping process leaves its state unchanged.
TASK_STOPPED Process execution has been stopped:
The process list To allow an efficient search through processes of a given
type the kernel creates several lists of processes. Each list consists of
pointers to process descriptors
12
Self-Instructional Material
child_stack Specifies the User Mode stack pointer to be assigned to the esp
Open Source Operating
register of the child Systems
The kernel invokes the do_fork( ) function, which executes the following
steps:
NOTES
1. If the CLONE_PID flag has been specified, the do_fork( ) function checks
whether the PID of the parent process is not null; if so, it returns an error
code.
2. The alloc_task_struct( ) function is invoked in order to get a new 8 KB
union task_union memory area to store the process descriptor and the Kernel
Mode stack of the new process.
3. The function follows the current pointer to obtain the parent process
descriptor and copies it into the new process descriptor in the memory area
just allocated.
4. A few checks occur to make sure the user has the resources necessary to
start a new process. First, the function checks whether
current>rlim[RLIMIT_NPROC] if so, an error code is returned.
5. The find_empty_process( ) function is invoked. This function checks
whether nr_tasks is smaller 2 than NR_TASKS-
MIN_TASKS_LEFT_FOR_ROOT. If so, it invokes get_free_taskslot( ) to
find a free entry in the task array. Otherwise, it returns an error.
6. The function writes the new process descriptor pointer into the previously
obtained task entry and sets the tarray_ptr field of the process descriptor to
the address of that entry
7. Now the function has taken almost everything that it can use from the
parent process; the rest of its activities focus on setting up new resources in
the child. First, the function invokes the get_pid( ) function to obtain a new
PID, which will be assigned to the child process
8. The function then updates all the process descriptor fields that cannot be
inherited from the parent process.
9. It invokes copy_thread( ) to initialize the Kernel Mode stack of the child
process with the values contained in the CPU registers when the clone( ) call
was issued
10. It uses the SET_LINKS macro to insert the new process descriptor in the
process list.
11. It uses the hash_pid( ) function to insert the new process descriptor in the
pidhash hash table.
12. It increments the values of nr_tasks and current->user->count.
13. It sets the state field of the child process descriptor to TASK_RUNNING
and then invokes sake_up_process( ) to insert the child in the runqueue list.
13
Self-Instructional Material
14. If the CLONE_VFORK flag has been specified, the function suspends
Open Source Operating the parent process until the child releases its memory address space. In order
Systems
to do this, the process descriptor includes a kernel semaphore called
vfork_sem
15. It returns the PID of the child, which will be eventually be read by the
parent process in User Mode. Now we have a complete child process in the
NOTES
runnable state. The child process will execute the same code as the parent,
except that the fork will return a null PID.
14
Self-Instructional Material
5. Uses the REMOVE_LINKS macro to unlink the process descriptor from
Open Source Operating
the process list. Systems
6. Invokes the free_task_struct( ) function to release the 8 KB memory area
used to contain the process descriptor and the Kernel Mode stack.
NOTES
15
Self-Instructional Material
in which software source code is generally available for inspection,
Open Source Operating independent peer review, and rapid evolution.
Systems
5. The lack of a dual mode i.e. user mode and kernel mode in an operating
system can cause serious problems. Some of these are: A running user
program can accidentally wipe out the operating system by overwriting it
with user data. Multiple processes can write in the same system at the
NOTES same time, with disastrous results. E.g., These problems could have
occurred in the MS-DOS operating system which had no mode bit and so
no dual mode.
2.8 SUMMARY
Open-source software, like Linux, is developed collectively over the
Internet, which serves as an electronic bazaar for innovative ideas.
Linux, like all other versions of UNIX, is a real multitasking system,
allowing multiple users to run many programs on the same system at
once.
The system starts in kernel mode when it boots and after the operating
system is loaded, it executes applications in user mode.
The system is in user mode when the operating system is running a user
application such as handling a text editor.
2.9 KEYWORDS
GNU software support : Linux supports a wide range of free software
written by the GNU Project, including utilities such as the GNU C and C++
compiler, gawk, groff, and so on.
X Window System : The X Window System is the de facto industry
standard graphics system for UNIX machines. A free version of The X
Window System (known as “Xfree86”) is available for Linux.
Virtual memory and shared libraries: Linux also implements shared
libraries, allowing programs which use standard subroutines to find the code
for these subroutines in the libraries at runtime.
16
Self-Instructional Material
3. Explain and illustrate User Mode and Kernel Mode in Operating
Open Source Operating
system and its necessity. Systems
17
Self-Instructional Material
Advanced Concepts
3.0 INTRODUCTION
This unit explains the advanced concepts of open source software with linx
where the scheduling and signals are discussed briefly. The development of
the open source software Linux is also discussed
3.1 OBJECTIVE
This unit helps the users to understand the advance concepts such as
Scheduling
Cloning
Personalities
Signals
Self-Instructional Material
for background jobs, avoidance of process starvation, reconciliation of the
Advanced Concepts
needs of low- and high-priority processes, and so on. The set of rules used to
determine when and how selecting a new process to run is called scheduling
policy. Linux scheduling is based on the time-sharing technique several
processes are allowed to run "concurrently," NOTES
Direct invocation
The scheduler is invoked directly when the current process must be blocked
right away because the resource it needs is not available. In this case, the
kernel routine that wants to block it proceeds as follows:
1. Inserts current in the proper wait queue
2. Changes the state of current either to TASK_INTERRUPTIBLE or to
PROCESS TASK_UNINTERRUPTIBLE 4
3. Invokes schedule( )
19
Self-Instructional Material
4. Checks if the resource is available; if not, goes to step 2
Advanced Concepts
5. Once the resource is available, removes current from the wait queue
Lazy invocation
NOTES The scheduler can also be invoked in a lazy way by setting the need_resched
field of current to 1. Actions performed by schedule( )
1. The schedule( ) function starts by running the functions left by other
kernel control paths in various queues. The function invokes
run_task_queue(&tq_scheduler); The function then executes all active
unmasked bottom halves.
2. Now comes the actual scheduling, and therefore a potential process
switch. The value of current is saved in the prev local variable. First, a check
is made to determine whether prev is a Round Robin real-time process that
has exhausted its quantum. If so, schedule( ) assigns a new quantum to prev
and puts it at the bottom of the runqueue list:
3. schedule( ) examines the state of prev. If it has nonblocked pending
signals and its state is TASK_INTERRUPTIBLE, the function wakes up the
process as Task_running.
4. If prev is not in the TASK_RUNNING state, prev must be removed from
the runqueue list:
5. Next, schedule( ) must select the process to be executed in the next time
quantum. To that the function scans the runqueue list. The objective is to
store in next the process descriptor pointer of the highest priority process.
schedule( ) repeatedly invokes the goodness( ) function on the runnable
processes to determine the best candidate:
6. A further check must be made at the exit of the loop to determine whether
c is 0. This occurs only when all the processes in the runqueue list have
exhausted their quantum
7. If a process other than prev has been selected, a process switch must take
place. Before performing it, however, the context_swtch field of kstat is
increased by 1 to update the statistics maintained by the kernel.
3.3 SIGNALS
A signal is a very short message that may be sent to a process or to a group
of processes. The only information given to the process is usually the
number identifying the signal. A set of macros whose names start with the
prefix SIG is used to identify signals; For example, the SIGCHLD macro
yields the identifier of the signal that is sent to a parent process when some
child stops or terminates.
Signals serve two main purposes:
To make a process aware that a specific event has occurred
20
Self-Instructional Material
To force a process to execute a signal handler function included in its
Advanced Concepts
code
The kernel distinguishes two different phases related to signal transmission:
NOTES
Signal sending The kernel updates the descriptor of the destination process to
represent that a new signal has been sent. Signal receiving The kernel forces
the destination process to react to the signal by changing its execution state
or by starting the execution of a specified signal handler or both. The
following factors must be taken into consideration:
• Signals are usually received only by the currently running process
• Signals of a given type may be selectively blocked by a process; in this
case, the process will not receive the signal until it removes the block.
3.3.1 Process
Actions Performed upon Receiving a Signal 5 There are three ways in which
a process can respond to a signal:
• Explicitly ignore the signal.
• Execute the default action associated with the signal
Abort
The process is destroyed. Dump The process is destroyed and a core file
containing its execution context is created.
Ignore
The signal is ignored. Stop- The process is stopped, that is, put in a
TASK_STOPPED state
Continue If the process is stopped (TASK_STOPPED), it is put into the
TASK_RUNNING
state. Catch the signal by invoking a corresponding signal-handler function.
21
Self-Instructional Material
1. The send_sig_info( ) function starts by checking whether the parameters
Advanced Concepts are correct:
if (sig < 0 || sig > 64) return -EINVAL;
2. The function checks then if the signal is being sent by a User Mode
NOTES process.
3. If the signal is sent by a User Mode process, the function determines
whether the operation is allowed. If the sig parameter has the value 0, the
function returns immediately without sending any signal: since is not a valid
signal number. Some types of signals might nullify other pending signals for
the destination process.
4. Next, send_sig_info( ) checks whether the new signal can be handled
immediately.
If ignored_signal( ) returns 1, the siginfo_t table of the destination process
must not be Updated. If ignored_signal( ) returns 0, the phase of signal
receiving has to be deferred, therefore send_sig_info( ) may have to modify
the data structures of the destination process. Since standard signals are not
queued, send_sig_info( ) must check whether another instance of the same
signal is already pending, then leave its mark on the proper data structures of
the process descriptor. The sigaddset() function is invoked to set the proper
bit in t->signal. The t->sigpending flag is also set, unless the destination
process has blocked the sig signal. The function terminates in the usual way
by waking up.
3.4 PROCESS
Oldest The address of a variable where the function is supposed to save the
bit mask array of 6 blocked signals. The heart of the do_signal( ) function
consists of a loop that repeatedly invokes dequeue_signal( ) until no more
nonblocked pending signals are left. The return code of dequeue_signal( ) is
stored in the signr local variable: if its value is 0, it means that all pending
signals have been handled and do_signal( ) can finish
22
Self-Instructional Material
sys_wait4( ) service routine of the wait4( ) system call is invoked to force the
Advanced Concepts
process to read information about its children.
3.5 CLONING
A clone process is created, using primitive type clone, by duplicating its
parent process. But, unlike classical processes, it may share its context with
its parent.
The standard form of the clone function is as follows:
int clone(int (*fn)(), void *child stack, int flag, int nargs,…);
The parameter fn is the pointer from the child process to the function
to be executed.
However, it is not necessary to have the source code in order to make a clone
of a program. In fact, having access to the source code can be undesirable
because it could subconsciously influence a programmer and result in
imitation of part of the code rather than creating entirely original code. A
23
Self-Instructional Material
variety of techniques have been developed for cloning software, including
Advanced Concepts reimplementation from official documentation accompanying the software
and from unofficial documentation. Reverse engineering becomes
particularly important when the documentation is incomplete, which is often
the case. Among the ways in which reverse engineering can be accomplished
NOTES are through observation of information exchange, disassembly using a
disassembler and decompilation using a decompiler. A compiler converts
source code into machine language, which can be read directly by a
computer's CPU (central processing unit); a decompiler attempts to convert
machine language back into source code. An assembler is a program that
translates an assembly language (which is a very low level language close to
machine language) into machine language.
There are several reasons for cloning software. One is that it is a way of
avoiding the high licensing fees and severe restrictions on use that typically
exist for proprietary (i.e., commercial) software. These include the lack of
availability of the source code and prohibitions on reverse engineering, and
thus a consequent lack of ability to study, modify or improve the software. A
second is that it is a way of making new software that is compatible with
existing software. In addition, some programmers regard it as a challenge or
a hobby.Cloning can be legal if there is no violation of the copyright of the
original software. There can be no such violation if the source code is not
available.
Copyright is the power granted by a government to the creator of a creative
work (e.g., the source code for a program, a magazine article, a poem, a
painting or a musical composition) that gives that creator the exclusive,
although transferable, right to copy or perform that work for a defined period
of time. Copyrights do not protect facts, discoveries, inventions, ideas or
methods of operation; they only protect the specific way in which they are
expressed in any type of medium (e.g., words, drawings, photographs or
musical notation).However, there might also be the murky issue of software
patents to contend with. In some cases, patents can be violated even if the
source code is entirely original. This is because patents may cover
functionality, whereas copyrights cover only wording. There are many
complex issues that remain to be resolved with regard to software patents,
and whether patents should even be permitted for software remains highly
contentious.
MINIX is a clone of UNIX that was written in 1987 for use in computer
science classes because of a sudden reversal in policy that prohibited the
formerly freely available UNIX source code from being available to
students. Linux is a UNIX clone that was developed in 1991 because of the
desire for a more powerful operating system than the then widely used MS-
DOS to take full advantage of the capabilities of the new Intel 386 processor.
It was also written because of the very high licensing fees for UNIX and
because of some dissatisfaction with MINIX, including the fact that it lacked
some of the features of UNIX and because of its lower but still significant
licensing fees.
24
Self-Instructional Material
Linux, MINIX and other UNIX clones are commonly referred to as Unix-
Advanced Concepts
like operating systems. Actually, this term is usually used in a broader sense
to include all operating systems that have the major characteristics of the
original UNIX as originally written by Ken Thompson at Bell Labs in 1969
and as subsequently developed at both Bell Labs and the University of NOTES
California at Berkeley (UCB), regardless of whether they are clones or have
some direct lineage from the original source code.
Clones are generally cheaper than the original software, and in many cases
they are free software (i.e., software that is free both in a monetary sense and
with regard to use). However, they are not necessarily inferior. In fact, in
some cases they are as good as or superior to the originals, as is clearly
illustrated by Linux. They also frequently have the benefit of providing
competition for the original software, thereby stimulating its developers to
improve its performance and features and to lower its price. In contrast to
proprietary software, there is no reason to make clones of free software. This
is because, by definition, the source code for free software is freely available
to anyone to use for any purpose, including modification and redistribution
of such modified versions. Occasionally, there is sufficient dissatisfaction
with the way in which a free software program is being developed to result in
a project fork, which is the starting of a new development branch
independent of the the existing project but based on the same source code.
A second meaning of the word clone in a software context is to make an
exact copy of a file, directory or disk inclusive of any files and subdirectories
within that directory or disk.The term is also used in a hardware context.
Most notably, when IBM introduced its revolutionary IBM PC in 1981, other
companies decided to develop clones as a legal reimplementation from the
PC's documentation and through reverse engineering. Because most of the
components were publicly available with the exception of the BIOS (basic
input output system), the only major task was reverse engineering the BIOS.
The term clone has other meanings in other contexts. It has become widely
used in the field of biotechnology in recent years to refer to an organism (i.e.,
an animal or plant) that is produced asexually (i.e., with only a single parent)
from a single cell of its parent and is genetically identical to that parent.
Unfortunately, in contrast to software cloning, the results of biological
cloning have not been entirely satisfactory to date in that that the cloned
individuals have been inferior to their parents, particularly with regard to life
expectancies.
3.6 PERSONALITIES
In order to allow programs coming from other operating system to be run in
Linux, Linux supports the idea of personalities. Each process is assigned to
an execution domain. This domain specifies the way in which system calls
are carried out, and the way in which messages are processed.
System calls: Linux uses software interrupts to change into kernel mode,
whilst other UNIX system use an inter- segment jump.
25
Self-Instructional Material
Message number specified by processes: When a process specifies a
Advanced Concepts message number, for example in calling the primitive sanction or kill, the
message number is converted by means of look-up-table
Number of messages sent to processes: when a message is to be sent to a
process, the message number is converted by means of look-up-table
NOTES
The system call personality allows a process to modify its execution domain
in order that Linux can emulate the behaviour of another operating system.
int personality(int pers);
It's Modular
Commercial Operating Systems normally get installed as a complete unit.
One cannot, for 7 example, install them without their Graphical User
Interface, or without its printing support - install everything or nothing.
Linux, on the other hand, is a very modular operating system. One could
install or run exactly the bits and pieces of Linux that are needed. In most
cases, the choice is on one of the predefined setups from the installation
menu, but is not compulsory. In some cases this makes a lot of sense. For
example, while setting up a server, one might want to disable the graphical
user interface once it is set up correctly, thus freeing up memory and the
processor for the more important task at hand.
26
Self-Instructional Material
It also allows the users to upgrade parts of the operating system without
Advanced Concepts
affecting the rest. For example, one could get the latest version of Gnome or
KDE without changing the kernel.
Also due to its modularity, there is more choice of components to use. One
example is the user interface. Many users choose KDE, which is very easy to
learn for users with Windows experience. Others choose Gnome, which is
more powerful but less similar to Windows. There are also several simple
alternatives for less-powerful computers, which make less demand on the
hardware available.
It’s Portable
Linux runs on practically every piece of equipment which qualifies as a
computer. It can be run on huge multiprocessor servers or a PDA. Apart
from Pentiums of various flavors, there are versions of Linux (called "ports")
on Atari, Amiga, Macintosh, PowerMac, PowerPC, NeXT, Alpha, Motorola,
MIPS, HP, PowerPC, Sun Sparc, Silicon Graphics, VAX/MicroVax, VME,
Psion 5, Sun UltraSparc, etc.
It is Stable
All applications can crash, but in many systems, the only recourse is to
switch off and reboot (and with some new "soft-switch" PCs, even that
doesn't work - you have to pull out the power cable). In comparison, Linux is
rock-solid. Every application runs independently of all others - if one
crashes, it crashes alone. Most Linux servers run for months on end, never
shutting down or rebooting. Even the GUI is independent of the kernel of the
operating system.
Self-Instructional Material
other 8 computer, running applications etc. as if they were on the local
Advanced Concepts system.
Multiple OS’ s on a PC
Dual options like having Windows as well as Linux are possible and one
NOTES could select which one of them to load every time you switch on. Linux can
read Windows' files - it supports the FAT and FAT32 file system’s, and
sometimes NTFS, so it's quite easy to transfer files from one operating
system to the other. The opposite, however, is not possible. Generally,
Windows applications cannot run under Linux, though there is a module
called WINE which runs various small Windows programs in Linux.
However, Open Office – an open source product loaded on to the Linux
system-- can read and write MS-Office files. There are also other office suite
options like Star Office, KOffice, GnomeOffice, WordPerfect Office, etc.
Can Windows and Linux machines interact via network? Definitely. You can
use SAMBA to share files or connect to shared directories or printers. With
SAMBA, the Linux computer could be set up function as a full NT server -
complete with authentication, file/printer sharing and so on. Apart from that,
Linux comes with excellent FTP, Web and similar services which are
accessible to all computers.
28
Self-Instructional Material
select another process to run. Be aware that a pre-empted process is
Advanced Concepts
not suspended, since it remains in the TASK_RUNNING state; it
simply no longer uses the CPU. The Linux kernel is not pre-emptive,
which means that a process can be pre-empted only while running in
User Mode NOTES
3. The Linux scheduling algorithm works by dividing the CPU time into
epochs. In a single epoch, every process has a specified time quantum
whose duration is computed when the epoch begins. The time
quantum value is the maximum CPU time portion assigned to the
process in that epoch. When a process has exhausted its time
quantum, it is pre-empted and replaced by another
4. A signal is a very short message that may be sent to a process or to a
group of processes.
To make a process aware that a specific event has occurred
To force a process to execute a signal handler function
included in its code
3.9 SUMMARY
The Linux scheduling algorithm works by dividing the CPU time into
epochs. In a single epoch, every process has a specified time quantum
whose duration is computed when the epoch begins.
The kernel checks whether there are nonblocked pending signals
before allowing a process to resume its execution in User Mode.
A clone process is created, using primitive type clone, by duplicating
its parent process. But, unlike classical processes, it may share its
context with its parent.
Copyright is the power granted by a government to the creator of a
creative work (e.g., the source code for a program, a magazine article,
a poem, a painting or a musical composition) that gives that creator
the exclusive, although transferable, right to copy or perform that
work for a defined period of time.
3.10 KEYWORDS
Process Pre-emption: Linux processes are pre-emptive. If a process enters
the TASK_RUNNING state, the kernel checks whether its dynamic priority
is greater than the priority of the currently running the execution of current
is interrupted and the scheduler is invoked to select another process to run.
29
Self-Instructional Material
runnable process. The epoch ends when all runnable processes have
Advanced Concepts exhausted their quantum.
Signal: A signal is a very short message that may be sent to a process or to a
group of processes.
NOTES System calls: Linux uses software interrupts to change into kernel mode,
whilst other UNIX system use an inter- segment jump.
Message number specified by processes: When a process specifies a
message number, for example in calling the primitive sanction or kill, the
message number is converted by means of look-up-table
30
Self-Instructional Material
BLOCK – II OPEN SOURCE DATABASE MySQL
Structure
4.0 Introduction
4.1 Introduction
4.2 MySQL
4.3 Setting up Account
4.4 Starting, terminating and writing your Own SQL programs
4.4.1 Connecting to the MySQL Server
4.5 Answers to Check Your Progress
4.6 Summary
4.7 Keywords
4.8 Self Assessment Questions and Exercises
4.9 Further Readings
4.0 INTRODUCTION
This unit explains the basic programming of MySQL by establishing and
connecting with the server with the root password and how to write own sql
programs.
4.1 INTRODUCTION
This unit helps the users to
Undertand and install mysql
Write own programs
4.2 MySQL
MySQL is the most popular open source SQL database management system
(DBMS). A fast, reliable, easy-to-use, multi-user multi-threaded relational
database system. It is freely available and released under GPL (GNU General
Public License). MySQL is a data storage area. In this storage area, there are
small sections called Tables.
Advantages
MySQL is Cross-Platform.
MySQL is fast.
MySQL is free.
Reliable and easy to use.
Multi-Threaded multi-user and robust SQL Database server.
31
Self-Instructional Material
Disadvantages
MySQL
Missing Sub-selects.
MySQL doesn't yet support the Oracle SQL extension.
Does not support Stored Procedures and Triggers.
NOTES MySQL doesn't support views, but this is on the TODO.
DROUP USER
RENAME USER
REVOKE
SET PASSWORD
32
Self-Instructional Material
CREATE USER
MySQL
Syntax:
CREATE USER user [IDENTIFIED BY [PASSWORD] 'password'] [, user
[IDENTIFIED BY [PASSWORD] 'password']] ...
NOTES
Example:
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
DROP USER
Syntax:
DROP USER user [, user] ...
Example:
DROP USER 'jeffrey'@'localhost';
RENAME USER
Syntax
RENAME USER old_user TO new_user [, old_user TO new_user] ...
Example
RENAME USER 'jeffrey'@'localhost' TO 'jeff'@'127.0.0.1';
SET PASSWORD
Syntax
SET PASSWORD [FOR user] =
{
PASSWORD('some password')
| OLD_PASSWORD('some password') | 'encrypted password'
}
Example:
SET PASSWORD FOR 'bob'@'%.loc.gov' =
PASSWORD('newpass');
33
Self-Instructional Material
4.4 Starting, terminating and writing your Own SQL programs
MySQL
Invoking MySQL Programs
To invoke a MySQL program from the command line (that is, from your
shell or command prompt), enter the program name followed by any options
NOTES or other arguments needed to instruct the program what you want it to do.
The following commands show some sample program invocations. “shell>”
represents the prompt for your command interpreter; it is not part of what
you type. The particular prompt you see depends on your command
interpreter. Typical prompts are $ for sh or bash, % for csh or tcsh, and C:\>
for the Windows command.com or cmd.exe command interpreters.
shell> mysql --user=root test
shell> mysqladmin extended-status variables
shell> mysqlshow --help
shell> mysqldump -u root personnel
Arguments that begin with a single or double dash (“-”, “--”) specify
program options. Options typically indicate the type of connection a program
should make to the server or affect its operational mode Non-option
arguments (arguments with no leading dash) provide additional information
to the program. For example, the mysql program interprets the first non-
option argument as a database name, so the command mysql --user=root test
indicates that you want to use the test database.
Some options are common to a number of programs. The most frequently
used of these are the --host (or -h), --user (or -u), and --password (or -p)
options that specify connection parameters. They indicate the host where the
MySQL server is running, and the username and password of your MySQL
account. All MySQL client programs understand these options; they allow
you to specify which server to connect to and the account to use on that
server. Other connection options are --port (or -P) to specify a TCP/IP port
number and --socket (or -S) to specify a Unix socket file on Unix (or named
pipe name on Windows). For more information on options that specify
connection options
You may find it necessary to invoke MySQL programs using the pathname
to the bin directory in which they are installed. This is likely to be the case if
you get a “program not found” error whenever you attempt to run a MySQL
program from any directory other than the bin directory. To make it more
convenient to use MySQL, you can add the pathname of the bin directory to
your PATH environment variable setting. That enables you to run a program
by typing only its name, not its entire pathname. For example, if mysql is
installed in /usr/local/mysql/bin, you can run the program by invoking it as
mysql, and it is not necessary to invoke it as /usr/local/mysql/bin/mysql.
Consult the documentation for your command interpreter for instructions on
setting your PATH variable. The syntax for setting environment variables is
34
Self-Instructional Material
interpreter-specific. (Some information is given in Section 4.2.4, “Setting
MySQL
Environment Variables”.) After modifying your PATH setting, open a new
console window on Windows or log in again on Unix so that the setting goes
into effect
35
Self-Instructional Material
shell> mysql --host=127.0.0.1
MySQL
shell> mysql --protocol=TCP
The --protocol option enables you to establish a particular type of connection
even when the other options would normally default to some other
NOTES protocol.On Windows, you can force a MySQL client to use a named-pipe
connection by specifying the --pipe or --protocol=PIPE option, or by
specifying . (period) as the host name. If named-pipe connections are not
enabled, an error occurs. Use the --socket option to specify the name of the
pipe if you do not want to use the default pipe name.
Connections to remote servers always use TCP/IP. This command connects
to the server running on remote.example.com using the default port number
(3306):
shell> mysql --host=remote.example.com
To specify a port number explicitly, use the --port or -P option:
shell> mysql --host=remote.example.com --port=13306
You can specify a port number for connections to a local server, too.
However, as indicated previously, connections to localhost on Unix will use
a socket file by default. You will need to force a TCP/IP connection as
already described or any option that specifies a port number will be ignored.
For this command, the program uses a socket file on Unix and the --port
option is ignored:
shell> mysql --port=13306 --host=localhost
To cause the port number to be used, invoke the program in either of these
ways:
shell> mysql --port=13306 --host=127.0.0.1
shell> mysql --port=13306 --protocol=TCP
The following options may be used to control how client programs connect
to the server:
--host=host_name, -h host_name
The host where the server is running. The default value is localhost.
--password[=pass_val], -p[pass_val]
The password of the MySQL account. As described earlier, the password
value is optional, but if given, there must be no space between -p or --
password= and the password following it. The default is to send no
password.
--pipe, -W
36
Self-Instructional Material
On Windows, connect to the server via a named pipe. This option applies for
MySQL
connections to a local server only. The server must have been started with
the --enable-named-pipe option to enable named-pipe connections.
--port=port_num, -P port_num
The port number to use for the connection, for connections made via TCP/IP. NOTES
The default port number is 3306.
--protocol={TCP|SOCKET|PIPE|MEMORY}
This option explicitly specifies a protocol to use for connecting to the server.
It is useful when the other connection parameters normally would cause a
protocol to be used other than the one you want. For example, connections
on Unix to localhost are made via a Unix socket file by default:
shell> mysql --host=localhost
To force a TCP/IP connection to be used instead, specify a --protocol option:
shell> mysql --host=localhost --protocol=TCP
To start the mysql program, try just typing its name at your command-line
prompt. If mysql starts up correctly, you’ll see a short message, followed by
a mysql> prompt that indicates the program is ready to accept queries. To
illustrate, here’s what the welcome message looks like (to save space, I
won’t show it in any further examples):
Self-Instructional Material
connection parameter options are shown in the following table. These
MySQL options have both a single-dash short form and a double-dash long form.
% mysql -pEnter password: ← enter your password here
If you like, you can specify the password directly on the command line by
NOTES using either - ppassword (note that there is no space after the -p) or --
password=password. I don’t recommend doing this on a multiple-user
machine, because the password may be visible momentarily to other users
who are running tools such as ps that report process information. If you get
an error message that mysql cannot be found or is an invalid command when
you try to invoke it,.To terminate a mysql session, issue a QUIT statement:
mysql> QUIT
You can also terminate the session by issuing an EXIT statement or (under
Unix) by typing Ctrl-D.The way you specify connection parameters for
mysql also applies to other MySQL programs such as mysqldump and
mysqladmin.
CREATE USER
DROUP USER
RENAME USER
REVOKE
SET PASSWORD
38
Self-Instructional Material
4. To invoke a MySQL program from the command line (that is, from
MySQL
your shell or command prompt), enter the program name followed by
any options or other arguments needed to instruct the program what
you want it to do. The following commands show some sample
program invocations. “shell>” represents the prompt for your
command interpreter NOTES
5. The advantages of MySQL are
MySQL is Cross-Platform.
MySQL is fast.
MySQL is free.
Reliable and easy to use.
Multi-Threaded multi-user and robust SQL Database server.
4.6 SUMMARY
In order to provide access the MySQL database you need to create an
account to use for connecting to the MySQL server running on a
given host.
To invoke a MySQL program from the command line (that is, from
your shell or command prompt), enter the program name followed by
any options or other arguments needed to instruct the program what
you want it to do.
You can also terminate the session by issuing an EXIT statement or
(under Unix) by typing Ctrl-D.
To start the mysql program, try just typing its name at your
command-line prompt. If mysql starts up correctly, you’ll see a short
message, followed by a mysql> prompt that indicates the program is
ready to accept queries.
4.7 KEYWORDS
MySQL: It is the most popular open source SQL database management
system (DBMS).
User names: It is used by MySQL for authentication purposes, have nothing
to do with user names (login names) as used by Windows or UnixMySQL
user names can be up to 16 characters long.
39
Self-Instructional Material
Long Answer questions:
MySQL 1. Explain the Process involved in Connecting to the MySQL Server.
NOTES Rémy Card, Eric Dumas, and Franck Mével. The Linux kernel book. John
Wiley & Sons, Inc., 2003.
Rasmus Lerdorf and Levin Tatroe. Programming PHP. " O'Reilly Media,
Inc., 2002.
Martin C. Brown. Perl: The complete reference. 2nd Edition, Tata McGraw-
Hill Publishing Company Limited, Indian Reprint, 2009.
Steven Holzner. PHP: The complete reference. 2nd Edition, Tata McGraw-
Hill Publishing Company Limited, Indian Reprint, 2009.
40
Self-Instructional Material
Record Selection Technology
UNIT - 5
RECORD SELECTION TECHNOLOGY
Structure NOTES
5.0 Introduction
5.1 Objective
5.2 Record selection Technology
5.3 Working with Strings
5.4 Date and Time Functions
5.5 Answers to Check Your Progress
5.6 Summary
5.7 Keywords
5.8 Self Assessment Questions and Exercises
5.9 Further Readings
5.0 INTRODUCTION
This unit covers the Mysql commands for selection of records from the
tables and how strings are manipulated in Mysql and the date and time
functions used in Mysql are decribed with their syntax and examples
5.1 Objective
This unit helps the users to learn and understand the following
Record selection
41
Self-Instructional Material
Now your table with some data is ready. We will apply select command to
Record Selection Technology our table ( name student ) and fetch all the records.
SELECT * FROM `student`
That's all to get all the records from the table student. We have not placed
any restriction here and asked for all the fields with all the records. Now if
we want to restrict our results and get only name field from the table.
SELECT name FROM `student`
This will return only name field from the table. We can ask for more fields
and all field names we have to separate by comma. We can include as many
field names we want from a table.SELECT name, class FROM `student`
name class
Arnold Three
Asruid Five
42
Self-Instructional Material
Now we will go for bit more and restrict the number of records we are
Record Selection Technology
getting. We are interested say in only 3 records. Our command should return
3 records only. We will use SQL limit command. This will take two
parameters. One is the starting point and other is number of records required.
Say we are interested in 3 records starting from beginning. Our command
will be NOTES
SELECT * FROM `student` LIMIT 0,3
Related Tutorial
Copy data to new table
SQL Left Join
SQL UNION
This command with LIMIT command will return us 3 records starting from 0
( or first ) record. This is very important when we use this command with
ORDER BY command. Now let us try to list all the students who have come
in first 3 ranks. We are required to list here 3 records who have mark more
than the others. The top 3 students we want to display in order of first,
second and third. The order we can display are in by default in ascending
order but we require the listing should return in descending order so we will
get the highest ranked student at the top. Before that let us start with a simple
example of ORDER BY command.
SELECT * FROM `student` ORDER BY mark
This will display the records of students in the order of lowest mark to
highest mark.
43
Self-Instructional Material
With the addition of command DESC we can change the order of display to
Record Selection Technology keep the highest mark at the top of the list and lowest mark at the bottom of
the list. Now let us add the LIMIT command to display only the top 3
records. We already have the list in the order of highest mark to lowest mark
so by just limiting the number of records to 3 will give our required top three
NOTES student records.
SELECT * FROM `student` ORDER BY `mark` DESC LIMIT 0,3
This is the SQL query which will display top three students based on the
mark they scored. In the next section we will use sql WHERE clause to
restrict or filter the records.
44
Self-Instructional Material
Output: geeks_for_geeks
Record Selection Technology
6. FIND_IN_SET(): This function is used to find a symbol from a set of
symbols.
Syntax: SELECT FIND_IN_SET('b', 'a, b, c, d, e, f');
NOTES
Output: 2
7. FORMAT(): This function is used to display a number in the given
format.
Syntax: Format("0.981", "Percent");
Output: ‘98.10%’
8. INSERT(): This function is used to insert the data into a database.
Syntax: INSERT INTO database (geek_id, geek_name) VALUES (5000,
'abc');
Output: successfully updated
9. INSTR(): This function is used to find the occurrence of an alphabet.
Syntax: INSTR('geeks for geeks', 'e');
Output: 2 (the first occurrence of ‘e’)
Syntax: INSTR('geeks for geeks', 'e', 1, 2 );
Output: 3 (the second occurrence of ‘e’)
10. LCASE(): This function is used to convert the given string into lower
case.
Syntax: LCASE ("GeeksFor Geeks To Learn");
Output: geeksforgeeks to learn
11. LEFT(): This function is used to SELECT a sub string from the left of
given size or characters.
Syntax: SELECT LEFT('geeksforgeeks.org', 5);
Output: geeks
12. LENGTH(): This function is used to find the length of a word.
Syntax: LENGTH('GeeksForGeeks');
Output: 13
13. LOCATE(): This function is used to find the nth position of the given
word in a string.
45
Self-Instructional Material
Syntax: SELECT LOCATE('for', 'geeksforgeeks', 1);
Record Selection Technology
Output: 6
14.LOWER(): This function is used to convert the upper case string into
lower case.
NOTES
Syntax: SELECT LOWER('GEEKSFORGEEKS.ORG');
Output: geeksforgeeks.org
15.LPAD(): This function is used to make the given string of the given size
by adding the given symbol.
Syntax: LPAD('geeks', 8, '0');
Output: 000geeks
16.LTRIM(): This function is used to cut the given sub string from the
original string.
Syntax: LTRIM('123123geeks', '123');
Output: geeks
17. MID(): This function is to find a word from the given position and of the
given size.
Syntax: Mid ("geeksforgeeks", 6, 2);
Output: for
18. POSITION(): This function is used to find position of the first
occurrence of the given alphabet.
Syntax: SELECT POSITION('e' IN 'geeksforgeeks');
Output: 2
19.REPEAT(): This function is used to write the given string again and
again till the number of times mentioned.
Syntax: SELECT REPEAT('geeks', 2);
Output: geeksgeeks
20. REPLACE(): This function is used to cut the given string by removing
the given sub string.
Syntax: REPLACE('123geeks123', '123');
Output: geeks
21.REVERSE(): This function is used to reverse a string.
Syntax: SELECT REVERSE('geeksforgeeks.org');
46
Self-Instructional Material
Output: ‘gro.skeegrofskeeg’
Record Selection Technology
22.RIGHT(): This function is used to SELECT a sub string from the right
end of the given size.
Syntax: SELECT RIGHT('geeksforgeeks.org', 4);
NOTES
Output: ‘.org’
23.RPAD(): This function is used to make the given string as long as the
given size by adding the given symbol on the right.
Syntax: RPAD('geeks', 8, '0');
Output: ‘geeks000’
24.RTRIM(): This function is used to cut the given sub string from the
original string.
Syntax: RTRIM('geeksxyxzyyy', 'xyz');
Output: ‘geeks’
25.SPACE(): This function is used to write the given number of spaces.
Syntax: SELECT SPACE(7);
Output: ‘ ‘
26.STRCMP(): This function is used to compare 2 strings.
If string1 and string2 are the same, the STRCMP function will return 0.
If string1 is smaller than string2, the STRCMP function will return -1.
If string1 is larger than string2, the STRCMP function will return 1.
Syntax: SELECT STRCMP('google.com', 'geeksforgeeks.com');
Output: -1
27. SUBSTR(): This function is used to find a sub string from the a string
from the given position.
Syntax:SUBSTR('geeksforgeeks', 1, 5);
Output: ‘geeks’
28. SUBSTRING(): This function is used to find an alphabet from the
mentioned size and the given string.
Syntax: SELECT SUBSTRING('GeeksForGeeks.org', 9, 1);
Output: ‘G’
47
Self-Instructional Material
29. SUBSTRING_INDEX(): This function is used to find a sub string
Record Selection Technology before the given symbol.
Syntax: SELECT SUBSTRING_INDEX('www.geeksforgeeks.org', '.', 1);
Output: ‘www’
NOTES
30.TRIM(): This function is used to cut the given symbol from the string.
Syntax: TRIM(LEADING '0' FROM '000123');
Output: 123
31.UCASE(): This function is used to make the string in upper case.
Syntax: UCASE ("GeeksForGeeks");
Output:GEEKSFORGEEKS
Output:
2017-01-13
CURTIME(): Returns the current time. Example:
SELECT CURTIME();
Output:
08:05:15
DATE(): Extracts the date part of a date or date/time expression.
Example:For the below table named ‘Test’
48
Self-Instructional Material
Id Name BirthTime
Record Selection Technology
4120 Pratik 1996-09-26
16:44:15.581
Output:
Name BirthDate
Pratik 1996-09-26
EXTRACT(): Returns a single part of a date/time. Syntax:
EXTRACT(unit FORM date);
There are several units that can be considered but only some are used such
as:
MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH,
QUARTER, YEAR, etc.
And ‘date’ is a valid date expression.
Example:
For the below table named ‘Test’
Id Name BirthTime
Queries
SELECT Name, Extract(DAY FROM BirthTime) AS BirthDay FROM Test;
Output:
Name BirthDay
Pratik 26
SELECT Name, Extract(YEAR FROM BirthTime) AS BirthYear FROM
Test;
Output:
Name BirthYear
Pratik 1996
49
Self-Instructional Material
SELECT Name, Extract(SECOND FROM BirthTime) AS BirthSecond
Record Selection Technology FROM Test;
Output:
Name BirthSecond
NOTES
Pratik 581
DATE_ADD() : Adds a specified time interval to a date
Syntax:
DATE_ADD(date, INTERVAL expr type);
Where, date – valid date expression and expr is the number of interval we
want to add.
Id Name BirthTime
Output:
Name BirthDayModified
Pratik 1996-10-26 16:44:15.581
SELECT Name, DATE_ADD(BirthTime, INTERVAL 4 HOUR) AS
BirthHourModified FROM Test;
Output:
50
Self-Instructional Material
Name BirthSecond
Record Selection Technology
Pratik 1996-10-26 20:44:15.581
DATE_SUB(): Subtracts a specified time interval from a date. Syntax for
DATE_SUB is same as DATE_ADD just the difference is that DATE_SUB
is used to subtract a given interval of date. NOTES
51
Self-Instructional Material
%k-Hour (0-23)
Record Selection Technology
%l-Hour (1-12)
%M-Month name (January-December)
52
Self-Instructional Material
5.5 ANSWERS TO CHECK YOUR PROGRESS Record Selection Technology
53
Self-Instructional Material
Record Selection Technology
5.6 SUMMARY
The SELECT statement is used to select data from a database. The
statement begins with the SELECT keyword.
String functions are used to perform an operation on input string and
NOTES return an output string.
In SQL, dates are complicated for newbies, since while working with
database, the format of the date in table must be matched with the
input date in order to insert.
With the addition of command DESC we can change the order of
display to keep the highest mark at the top of the list and lowest mark
at the bottom of the list.
5.7 KEYWORDS
SUBSTR(): This function is used to find a sub string from the a string from
the given position.
RTRIM(): This function is used to cut the given sub string from the original
string.
POSITION(): This function is used to find position of the first occurrence of
the given alphabet
54
Self-Instructional Material
Martin C. Brown. Perl: The complete reference. 2nd Edition, Tata
Record Selection Technology
McGraw-Hill Publishing Company Limited, Indian Reprint, 2009.
55
Self-Instructional Material
Working With Sql
UNIT- 6 WORKING WITH SQL
Structure
NOTES 6.0 Introduction
6.1 Objective
6.2 Sorting query Results
6.3 Generating Summary
6.4 Working with Metadata
6.4.1 Types of Metadata
6.4.2 Obtaining Metadata with SHOW
6.4.3 Obtaining Metadata with INFORMATION_SCHEMA
6.5 Using Sequences
6.5.1Creating a Sequence
6.5.2 Dropping a Sequence
6.6 My SQL and Web
6.6.1 Basic Web Page Generation
6.7 Answers to Check Your Progress
6.8 Summary
6.9 Keywords
6.10 Self Assessment Questions and Exercises
6.1 OBJECTIVE
This unit explains to users the following concepts
56
Self-Instructional Material
Description
Working With Sql
The MySQL ORDER BY clause is used to sort the records in your result set.
Syntax
NOTES
The syntax for the ORDER BY clause in MySQL is:
SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];
Parameters or Arguments
Expressions
The columns or calculations that you wish to retrieve.
Tables
The tables that you wish to retrieve records from. There must be at least one
table listed in the FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected.
ASC
Optional. It sorts the result set in ascending order by expression (default, if
no modifier is provider).
DESC
Optional. It sorts the result set in descending order by expression.
If the ASC or DESC modifier is not provided in the ORDER BY clause, the
results will be sorted by expression in ascending order. This is equivalent to
ORDER BY expression ASC. The ORDER BY clause can be used in a
SELECT statement, SELECT LIMIT statement, and DELETE LIMIT
statement in MySQL.
Example - Sorting without using ASC/DESC attribute
The MySQL ORDER BY clause can be used without specifying the ASC or
DESC modifier. When this attribute is omitted from the ORDER BY clause,
the sort order is defaulted to ASC or ascending order.
For example:
SELECT city
57
Self-Instructional Material
Working With Sql FROM customers
WHERE customer_name = 'Apple'
ORDER BY city;
NOTES
This MySQL ORDER BY example would return all records sorted by the
city field in ascending order and would be equivalent to the following
ORDER BY clause:
SELECT city
FROM customers
WHERE customer_name = 'Apple'
ORDER BY city ASC;
Most programmers omit the ASC attribute if sorting in ascending order.
Example - Sorting in descending order
When sorting your result set in descending order, you use the DESC attribute
in your ORDER BY clause as follows:
SELECT last_name, first_name, city
FROM contacts
WHERE last_name = 'Johnson'
ORDER BY city DESC;
This MySQL ORDER BY example would return all records sorted by the
city field in descending order.
Example - Sorting by relative position .You can also use the MySQL
ORDER BY clause to sort by relative position in the result set, where the
first field in the result set is 1. The next field is 2, and so on.
For example:
SELECT last_name, first_name, city
FROM contacts
WHERE last_name = 'Johnson'
ORDER BY 3 DESC;
This MySQL ORDER BY would return all records sorted by the city field in
descending order, since the city field is in position #3 in the result set and
would be equivalent to the following ORDER BY clause:
SELECT last_name, first_name, city
58
Self-Instructional Material
FROM contacts
Working With Sql
WHERE last_name = 'Johnson'
ORDER BY city DESC;
NOTES
Example - Using both ASC and DESC attributes
When sorting your result set using the MySQL ORDER BY clause, you can
use the ASC and DESC attributes in a single SELECT statement.
For example:
SELECT supplier_city, supplier_state
FROM suppliers
WHERE supplier_name = 'Microsoft'
ORDER BY supplier_city DESC, supplier_state ASC;
This MySQL ORDER BY would return all records sorted by the
supplier_city field in descending order, with a secondary sort by
supplier_state in ascending order.
Self-Instructional Material
Working With Sql The preceding examples include two common summary types: counting
summaries and content summaries. The first (the number of customer
records per state) is a counting summary. The content of each record is
important only for purposes of placing it into the proper group or category
for counting. Such summaries are essentially histograms, where you sort
NOTES items into a set of bins and count the number of items in each bin. The
second example (sales volume per month) is a content summary, in which
sales totals are based on sales values in order records.
Another summary type produces neither counts nor sums, but simply a list of
unique values. This is useful if you care which values are present rather than
how many of each there are. To determine the states in which you have
customers, you need a list of the distinct state names contained in the
records, not a list consisting of the state value from every record.
Using aggregate function we can achieve summary of values. Aggregate
functions are COUNT (), MIN (), MAX (), SUM. (), AVG () and GROUP
BY clause to group the rows into subsets and obtain an aggregate value for
each one.To getting a list of unique values, use SELECT DISTINCT rather
than SELECT.Using COUNT (DISTINCT) - To count how many distinct
values there are
60
Self-Instructional Material
Sorting Query Results
Working With Sql
SQL SELECT command to fetch data from MySQL table. When you select
rows, the MySQL server is free to return them in any order, unless you
instruct it otherwise by saying how to sort the result. But a query doesn't
come out in the order you want NOTES
Information about the MySQL server − This includes the status of the
database server, version number, etc.
61
Self-Instructional Material
Working With Sql Display information about columns or indexes in a table:
SHOW COLUMNS FROM tbl_name;
SHOW INDEX FROM tbl_name;
NOTES
The DESCRIBE tbl_name and EXPLAIN tbl_name statements are
synonymous with SHOW COLUMNS FROM tbl_name.
Display descriptive information about tables in the default database or in a
given database:
SHOW TABLE STATUS;
SHOW TABLE STATUS FROM db_name;
Several forms of the SHOW statement take a LIKE 'pattern' clause
permitting a pattern to be given that limits the scope of the output. MySQL
interprets 'pattern' as an SQL pattern that may include the ‘%’ and ‘_’
wildcard characters.
6.5.1Creating a Sequence
CREATE SEQUENCE sequence_name
62
Self-Instructional Material
[INCREMENT BY #]
Working With Sql
[START WITH #]
[MAXVALUE # | NOMAXVALUE]
NOTES
[MINVALUE # | NOMINVALUE]
[CYCLE | NOCYCLE]
HTML
Self-Instructional Material
Working With Sql Static Web Page
A static web page shows the required information to the viewer, but do not
accept any information from the viewer
64
Self-Instructional Material
3. Summaries are useful when you want the overall picture, not the
Working With Sql
details. They’re more readily understood than a long list of records.
They enable you to answer questions such as “How many?” or “What
is the total?” or “What is the range of values?”
4. The types of metadata are
Information about the result of queries NOTES
Information about the tables and databases
Information about the MySQL server
5. SHOW statement that displays many types of database metadata.
SHOW is helpful for keeping track of the contents of your databases
and reminding yourself about the structure of your tables.
6.
6.8 SUMMARY
Database systems are useful for data storage and retrieval, but can
also summarize your data in more concise forms.
Information about the result of queries-This includes the number of
records affected by any SELECT, UPDATE or DELETE statement.
6.9 KEYWORDS
Sorting Query Results: SQL SELECT command to fetch data from MySQL
table. When you select rows, the MySQL server is free to return them in any
order, unless you instruct it otherwise by saying how to sort the result.
Static Web Page: A static web page shows the required information to the
viewer, but do not accept any information from the viewer
Dynamic Web Page: A dynamic web page displays the information to the
viewer and also accepts the information from the user Railway reservation,
Online shopping etc. are examples of dynamic web page.
Self-Instructional Material
Working With Sql
Rémy Card, Eric Dumas, and Franck Mével. The Linux kernel book.
NOTES John Wiley & Sons, Inc., 2003.
66
Self-Instructional Material
Php
BLOCK – III
OPEN SOURCE PROGRAMMING
LANGUAGE PHP NOTES
UNIT- 7 PHP
Structure
7.0 Introduction
7.1 Objective
7.2 PHP
7.2.1 Common uses of PHP
7.2.2 Characteristics of PHP
7.3 Programming in Web Environment
7.4 PHP Variables
7.4.1 Variable Scope
7.5 Constants
7.5.1 PHP Magic constants
7.6 Data Types
7.6.1 Integers
7.6.2 Doubles
7.6.3Boolean
7.6.4 NULL
7.6.5 Strings
7.6.6 Arrays
7.7 Operators
7.7.1Arithmetic Operators
7.7.2 Comparison Operators
7.7.3 Logical Operators
7.7.4 Assignment Operators
7.7.5 Conditional Operator
7.7.6 Operators Categories
7.7.7 Precedence of PHP Operators
7.8 Statement
7.9 Answers to Check Your Progress
7.10 Summary
7.11 Keywords
7.12 Self Assessment Questions and Exercises
7.13 Further Readings
67
Self-Instructional Material
Php 7.0 INTRODUCTION
Open source programming languages plays an pivotal role in creation of real
time applications as the software is freely available and it can be used with
good packages. The worked modules can be shared for later use of
NOTES developers. In this unit, the open source programming language PHP is
explained with the basics of programming
7.1 OBJECTIVE
After reading this unit you will be able to
Understand PHP
Learn the web environment
Basics of PHP
7.2 PHP
PHP started out as a small open source project that evolved as more and
more people found out how useful it was. Rasmus Lerdorf unleashed the first
version of PHP way back in 1994. PHP is a recursive acronym for "PHP:
Hypertext Pre-processor". PHP is a server side scripting language that is
embedded in HTML. It is used to manage dynamic content, databases,
session tracking, even build entire e-commerce sites. It is integrated with a
number of popular databases, including MySQL, PostgreSQL, Oracle,
Sybase, Informix, and Microsoft SQL Server.
PHP is pleasingly zippy in its execution, especially when compiled as an
Apache module on the UNIX side. The MySQL server, once started,
executes even very complex queries with huge result sets in record-setting
time. PHP supports a large number of major protocols such as POP3, IMAP,
and LDAP. PHP4 added support for Java and distributed object architectures
(COM and CORBA), making n-tier development a possibility for the first
time.
Simplicity
Efficiency
Security
68
Self-Instructional Material
Flexibility
Php
Familiarity
Local variables
69
Self-Instructional Material
Php Function parameters
Global variables
Static variables
Variable Naming
NOTES
Rules for naming a variable is –
7.5 CONSTANTS
A constant is a name or an identifier for a simple value. A constant value
cannot change during the execution of the script. By default, a constant is
case-sensitive. By convention, constant identifiers are always uppercase. A
constant name starts with a letter or underscore, followed by any number of
letters, numbers, or underscores. If you have defined a constant, it can never
be changed or undefined.
To define a constant you have to use define() function and to retrieve the
value of a constant, you have to simply specifying its name. Unlike with
variables, you do not need to have a constant with a $. You can also use the
function constant() to read a constant's value if you wish to obtain the
constant's name dynamically.
constant() function
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not
know its name, i.e. It is stored in a variable or returned by a function.
constant() example
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in
constants.
Differences between constants and variables are There is no need to write a
dollar sign ($) before a constant, where as in Variable one has to write a
dollar sign. Constants cannot be defined by simple assignment, they may
70
Self-Instructional Material
only be defined using the define () function. Constants may be defined and
Php
accessed anywhere without regard to variable scoping rules.
Once the Constants have been set, may not be redefined or undefined. Valid
and invalid constant names
NOTES
// Valid constant names
define("ONE", "first thing");
define("TWO2", "second thing");
define("THREE_3", "third thing");
// Invalid constant names
define("2TWO", "second thing");
define("__THREE__", "third value");
Self-Instructional Material
Php Booleans − have only two possible values either true or false.
NULL − is a special type that only has one value: NULL.
Strings − are sequences of characters, like 'PHP supports string operations.'
NOTES
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can package
up both other kinds of values and functions that are specific to the class.
Resources − are special variables that hold references to resources external
to PHP (such as database connections).
The first five are simple types, and the next two (arrays and objects) are
compound - the compound types can package up other arbitrary values of
arbitrary type, whereas the simple types cannot. We will explain only simple
data type in this chapters. Array and Objects will be explained separately.
7.6.1 Integers
They are whole numbers, without a decimal point, like 4195. They are the
simplest type .they correspond to simple whole numbers, both positive and
negative. Integers can be assigned to variables, or they can be used in
expressions, like so −
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base
16) format. Decimal format is the default, octal integers are specified with a
leading 0, and hexadecimals have a leading 0x.For most common platforms,
the largest integer is (2**31 . 1) (or 2,147,483,647), and the smallest (most
negative) integer is . (2**31 . 1) (or .2,147,483,647).
7.6.2 Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum
number of decimal places needed. For example, the code −
Live Demo
<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print("$many + $many_2 = $few <br>");
?>
72
Self-Instructional Material
It produces the following browser output −
Php
2.28888 + 2.21112 = 4.5
7.6.3 Boolean
They have only two possible values either true or false. PHP provides a NOTES
couple of constants especially for use as Booleans: TRUE and FALSE,
which can be used like so −
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
Interpreting other types as Booleans. Here are the rules for determine the
"truth" of any value not already of the Boolean type −If the value is a
number, it is false if exactly equal to zero and true otherwise. If the value is a
string, it is false if the string is empty (has zero characters) or is the string
"0", and is true otherwise. Values of type NULL are always false.
If the value is an array, it is false if it contains no other values, and it is true
otherwise. For an object, containing a value means having a member variable
that has been assigned a value. Valid resources are true (although some
functions that return resources when they are successful will return FALSE
when unsuccessful).Don't use double as Booleans.
Each of the following variables has the truth value embedded in its name
when it is used in a Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";
7.6.4 NULL
NULL is a special type that only has one value: NULL. To give a variable
the NULL value, simply assign it like this −
$my_var = NULL;
73
Self-Instructional Material
Php The special constant NULL is capitalized by convention, but actually it is
case insensitive; you could just as well have typed −
$my_var = null;
NOTES A variable that has been assigned NULL has the following properties −It
evaluates to FALSE in a Boolean context. It returns FALSE when tested
with IsSet() function.
7.6.5 Strings
They are sequences of characters, like "PHP supports string operations".
Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = 'This is a somewhat longer, singly quoted string';
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted
strings replace variables with their values as well as specially interpreting
certain character sequences.
Live Demo
<?php
$variable = "name";
$literally = 'My $variable will not print!';
print($literally);
print "<br>";
$literally = "My $variable will print!";
print($literally);
?>
This will produce following result −
My $variable will not print!
My name will print
7.6.6 Arrays
An array is a data structure that stores one or more similar type of values in
a single value. For example if you want to store 100 numbers then instead
of defining 100 variables its easy to define an array of 100 length.
74
Self-Instructional Material
There are three different kind of arrays and each array value is accessed Php
using an ID c which is called array index.
7.7 OPERATORS
PHP language supports following type of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
7.7.1Arithmetic Operators
There are following arithmetic operators supported by PHP language
.Assume variable A holds 10 and variable B holds 20 then
Show Examples
Self-Instructional Material
Php 7.7.2 Comparison Operators
There are following comparison operators supported by PHP
languageAssume variable A holds 10 and variable B holds 20 then
Show Examples
NOTES
Operator Description Example
76
Self-Instructional Material
Operator Description Example
Php
Called Logical AND
operator. If both the
and (A and B) is true.
operands are true then
condition becomes true. NOTES
Called Logical OR
Operator. If any of the
or two operands are non (A or B) is true.
zero then condition
becomes true.
Called Logical OR
Operator. If any of the
|| two operands are non (A || B) is true.
zero then condition
becomes true.
Simple assignment
operator, Assigns values C = A + B will assign
=
from right side operands value of A + B into C
to left side operand
77
Self-Instructional Material
Php result to left operand
Subtract AND
assignment operator, It
subtracts right operand C -= A is equivalent to
-=
NOTES from the left operand C=C-A
and assign the result to
left operand
Multiply AND
assignment operator, It
multiplies right operand C *= A is equivalent to
*=
with the left operand C=C*A
and assign the result to
left operand
Modulus AND
assignment operator, It
C %= A is equivalent to
%= takes modulus using
C=C%A
two operands and assign
the result to left operand
Self-Instructional Material
Php
Unary prefix operators, which precede a single operand.
7.8 STATEMENT
A prepared statement is a feature used to execute the same (or similar) SQL
statements repeatedly with high efficiency.Prepared statements basically
work like this:
79
Self-Instructional Material
Php Prepare: An SQL statement template is created and sent to the database.
Certain values are left unspecified, called parameters (labeled "?"). Example:
INSERT INTO MyGuests VALUES(?, ?, ?)The database parses, compiles,
and performs query optimization on the SQL statement template, and stores
the result without executing it
NOTES
Execute: At a later time, the application binds the values to the parameters,
and the database executes the statement. The application may execute the
statement as many times as it wants with different values.Compared to
executing SQL statements directly, prepared statements have three main
advantages:
80
Self-Instructional Material
3. Scope can be defined as the range of availability a variable has to the
Php
program in which it is declared. PHP variables can be one of four
scope types:
NOTES
Local variables
Function parameters
Global variables
Static variables
Variable Naming
7.10 SUMMARY
An array is a data structure that stores one or more similar type of
values in a single value. For example if you want to store 100
numbers then instead of defining 100 variables its easy to define an
array of 100 length.
Resources are special variables that hold references to resources
external to PHP (such as database connections).
7.11 KEYWORDS
Numeric array − An array with a numeric index. Values are stored and
accessed in linear fashion
Boolean: They have only two possible values either true or false. PHP
provides a couple of constants especially for use as Booleans: TRUE and
FALSE,
Resources: They are special variables that hold references to resources
external to PHP (such as database connections).
Constants: A constant is a name or an identifier for a simple value. A
constant value cannot change during the execution of the script.
81
Self-Instructional Material
Php
82
Self-Instructional Material
Functions
UNIT- 8 FUNCTIONS
NOTES
Structure
8.0 Introduction
8.1 Objective
8.2Functions
8.2.1 Creating PHP Function
8.2.2 PHP Functions with Parameters
8.2.3 Passing Arguments by Reference
8.2.4 PHP Functions Returning Value
8.2.5 Setting Default Values for Function Parameter
8.2.6 Dynamic Function Calls
8.3 Arrays
8.3.1 Numeric Array
8.3.2 Associative Arrays
8.3.3 Multidimensional Arrays
8.4 Object Oriented Concepts
8.4.1 Defining PHP Classes
8.4.2 Creating Objects in PHP
8.4.3 Calling Member Functions
8.4.4Constructor Functions
8.4.5 Function Overriding
8.4.6 Interfaces
8.5. String Manipulation and Regular Expression
8.5.1 String Concatenation Operator
8.6 File Handling and Data Storage
8.6.1The include() Function
8.6.2 The require() Function
8.7 Answers to Check Your Progress
8.8 Summary
8.9 Keywords
8.10 Self Assessment Questions and Exercises
8.11 Further Readings
8.0 INTRODUCTION
The programming of PHP with functions helps for the manipulation of data in
a much easier manner. The file handling functions and the storage of data is
helpful for the usage of large databases. IN this unit, the functions of PHP
and its usage with files and strings are explained.
83
Self-Instructional Material
Functions 8.1 OBJECTIVE
This unit helps the user to understand the following concepts
Function
NOTES Strings
Arrays
OOP
Regular Expression
File Handling
8.2 FUNCTIONS
PHP functions are similar to other programming languages. A function is a
piece of code which takes one more input in the form of parameter and does
some processing and returns a value. You already have seen many functions
like fopen() and fread() etc. They are built-in functions but PHP gives you
option to create your own functions as well. There are two parts which should
be clear to you
In fact you hardly need to create your own PHP function because there are
already more than 1000 of built-in library functions created for different area
and you just need to call them according to your requirement. Please refer to
PHP Function Reference for a complete set of useful functions.
Self-Instructional Material
/* Defining a PHP Function */
Functions
function writeMessage() {
echo "You are really a nice person, Have a nice time!"; NOTES
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result −
You are really a nice person, Have a nice time!
Self-Instructional Material
Functions This will display following result −
Sum of the two numbers is : 30
86
Self-Instructional Material
This will display following result −
Functions
Original Value is 10
Original Value is 16 NOTES
Self-Instructional Material
Functions Live Demo
<html>
<head>
NOTES <title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function printMe($param = NULL) {
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
This will produce following result
This is test
88
Self-Instructional Material
</body>
Functions
</html>
This will display following result NOTES
Hello
8.3 ARRAYS
An array is a data structure that stores one or more similar type of values in a
single value. For example if you want to store 100 numbers then instead of
defining 100 variables its easy to define an array of 100 length. is called
array index.
Self-Instructional Material
Functions $numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
NOTES
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Self-Instructional Material
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
Functions
echo "Salary of zara is ". $salaries['zara']. "<br />";
/* Second method to create array. */ NOTES
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>
This will produce the following result −
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
91
Self-Instructional Material
Functions "maths" => 30,
"chemistry" => 39
),
NOTES
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
This will produce the following result −
Marks for mohammad in physics: 35
Marks for qadir in maths: 32
Marks for zara in chemistry: 39
92
Self-Instructional Material
8.4 OBJECT ORIENTED CONCEPTS Functions
Before we go in detail, let’s define important terms related to Object Oriented
Programming.
NOTES
Class − this is a programmer-defined data type, which includes local
functions as well as local data. You can think of a class as a template for
making many instances of the same kind (or class) of object.
Object − an individual instance of the data structure defined by a class. You
define a class once and then make many objects that belong to it. Objects are
also known as instance.
Member Variable − these are the variables defined inside a class. This data
will be invisible to the outside of the class and can be accessed via member
functions. These variables are called attribute of the object once an object is
created.
Member function − these are the function defined inside a class and are used
to access object data.
Inheritance − When a class is defined by inheriting existing function of a
parent class then it is called inheritance. Here child class will inherit all or
few member functions and variables of a parent class.
Parent class − A class that is inherited from by another class. This is also
called a base class or super class.
Child Class − A class that inherits from another class. This is also called a
subclass or derived class.
Polymorphism − this is an object oriented concept where same function can
be used for different purposes. For example function name will remain same
but it takes different number of arguments and can do different task.
Overloading − a type of polymorphism in which some or all of operators
have different implementations depending on the types of their arguments.
Similarly functions can also be overloaded with different implementation.
Data Abstraction − any representation of data in which the implementation
details are hidden (abstracted).
Encapsulation − refers to a concept where we encapsulate all the data and
member functions together to form an object.
Constructor − refers to a special type of function which will be called
automatically whenever there is an object formation from a class.
Destructor − refers to a special type of function which will be called
automatically whenever an object is deleted or goes out of scope.
Self-Instructional Material
Functions <?php
class phpClass {
var $var1;
NOTES
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
[..]
}
[..]
}
?>
Here is the description of each line −The special form class, followed by the
name of the class that you want to define. A set of braces enclosing any
number of variable declarations and function definitions. Variable
declarations start with the special form var, which is followed by a
conventional $ variable name; they may also have an initial assignment to a
constant value. Function definitions look much like standalone PHP functions
but are local to the class and will be used to set and access object data.
Example
Here is an example which defines a class of Books type
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
94
Self-Instructional Material
}
Functions
function getTitle(){
echo $this->title ." <br/>"; NOTES
}
}
?>
95
Self-Instructional Material
Functions $chemistry->getPrice();
$maths->getPrice();
This will produce the following result
NOTES
Physics for High School
Advanced Chemistry
Algebra
10
15
7
Self-Instructional Material
This will produce the following result
Functions
Physics for High School
Advanced Chemistry NOTES
Algebra
10
15
7
Destructor
Like a constructor function you can define a destructor function using
function destruct(). You can release all the resources with-in a destructor.
Inheritance
PHP class definitions can optionally inherit from a parent class definition by
using the extends clause. The syntax is as follows
Following example inherits Books class and adds more functionality based on
the requirement.
class Novel extends Books {
var $publisher;
function setPublisher($par){
$this->publisher = $par;
}
97
Self-Instructional Material
Functions function getPublisher(){
echo $this->publisher. "<br />";
}
NOTES
}
Public Members
Unless you specify otherwise, properties and methods of a class are public.
That is to say, they may be accessed in three possible situations.
Till now we have seen all members as public members. If you wish to limit
the accessibility of the members of a class then you define class members as
private or protected.
Private members
By designating a member private, you limit its accessibility to the class in
which it is declared. The private member cannot be referred to from classes
that inherit the class in which it is declared and cannot be accessed from
outside the class.A class member can be made private by using private
keyword infront of the member.
98
Self-Instructional Material
class MyClass {
Functions
private $car = "skoda";
$driver = "SRK"; NOTES
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
private function myPrivateFunction() {
return("I'm not visible outside!");
}
}
When MyClass class is inherited by another class using extends,
myPublicFunction() will be visible, as will $driver. The extending class will
not have any awareness of or access to myPrivateFunction and $car, because
they are declared private.
Protected members
A protected property or method is accessible in the class in which it is
declared, as well as in classes that extend that class. Protected members are
not available outside of those two kinds of classes. A class member can be
made protected by using protected keyword in front of the member.Here is
different version of MyClass
class MyClass {
protected $car = "skoda";
$driver = "SRK";
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
99
Self-Instructional Material
Functions }
function myPublicFunction() {
return("I'm visible!");
NOTES
}
protected function myPrivateFunction() {
return("I'm visible in child class!");
}
}
8.4.6 Interfaces
Interfaces are defined to provide a common function names to the
implementers. Different implementors can implement those interfaces
according to their requirements. You can say, interfaces are skeletons which
are implemented by developers.As of PHP5, it is possible to define an
interface like below
interface Mail {
public function sendMail();
}
Then, if another class implemented that interface, like this −
class Report implements Mail {
// sendMail() Definition goes here
}
function toString() {
return($this->_lastName .", " .$this->_firstName);
}
}
class NameSub1 extends Name {
var $_middleInitial;
function NameSub1($first_name, $middle_initial, $last_name) {
Name::Name($first_name, $last_name);
$this->_middleInitial = $middle_initial;
}
100
Self-Instructional Material
function toString() {
Functions
return(Name::toString() . " " . $this->_middleInitial);
} NOTES
101
Self-Instructional Material
Functions Using the strlen() function
The strlen() function is used to find the length of a string.Let's find the length
of our string "Hello world!"
Regular Expressions
Regular expressions are nothing more than a sequence or pattern of
characters it. They provide the foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside a another
string, you can replace one string by another string and you can split a string
into many chunks.PHP offers functions specific to two sets of regular
expression functions, each corresponding to a certain type of regular
expression. You can use any of them based on your comfort.
Self-Instructional Material
PERL Style Regular Expressions
Functions
POSIX Regular Expressions
NOTES
The structure of a POSIX regular expression is not dissimilar to that of a
typical arithmetic expression: various elements (operators) are combined to
form more complex expressions.
The simplest regular expression is one that matches a single character, such
as g, inside strings such as g, haggle, or bag. Let’s give explanation for few
concepts being used in POSIX regular expression. After that we will
introduce you with regular expression related functions.
Brackets
Brackets ([]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.
[0-9]
It matches any decimal digit from 0 through 9.
Quantifiers
The frequency or position of bracketed character sequences and single
characters can be denoted by a special character. Each special character
having a specific connotation. The +, *, ?, {int. range}, and $ flags all follow
a character sequence.
Sr.No Expression & Description
1 p+ It matches any string containing at least one p
.
a p followed by zero or more instances of the sequence php.
103
Self-Instructional Material
Functions Sr.No Function & Description
1 ereg() The ereg() function searches a string specified by string
for a string specified by pattern, returning true if the pattern is found, and
false otherwise.
NOTES
104
Self-Instructional Material
Include
Functions
105
Self-Instructional Material
Functions
8.7 ANSWERS TO CHECK YOUR PROGRESS
1. The Concepts of PHP are:
Function
NOTES
Strings
Arrays
OOP
Regular Expression
File Handling
2. An array is a data structure that stores one or more similar type of
values in a single value. For example if you want to store 100
numbers then instead of defining 100 variables it’s easy to define an
array of 100 length. is called array index.
3. A multi-dimensional array each element in the main array can also be
an array. And each element in the sub-array can be an array, and so
on. Values in the multi-dimensional array are accessed using multiple
indexes.
4. Constructor Functions are special type of functions which are called
automatically whenever an object is created. So, we take full
advantage of this behaviour, by initializing many things through
constructor functions. PHP provides a special function called
construct () to define a constructor.
5. Function definitions in child classes override definitions with the
same name in parent classes. In a child class, we can modify the
definition of a function inherited from parent class.
8.8 SUMMARY
A multi-dimensional array each element in the main array can also be
an array.
Object is an individual instance of the data structure defined by a
class. You define a class once and then make many objects that
belong to it. Objects are also known as instance.
Polymorphism is an object oriented concept where same function can
be used for different purposes. For example function name will
remain same but it takes different number of arguments and can do
different task.
Overloading is a type of polymorphism in which some or all of
operators have different implementations depending on the types of
their arguments. Similarly functions can also be overloaded with
different implementation.
8.9 KEYWORDS
Function: A function is a piece of code which takes one more input in the
form of parameter and does some processing and returns a value.
Associative array: An array with strings as index. This stores element values
in association with key values rather than in a strict linear index order.
106
Self-Instructional Material
Multidimensional array: An array containing one or more arrays and values
Functions
are accessed using multiple indices
107
Self-Instructional Material
Php and Mysql Database
9.0 INTRODUCTION
The open source software PHP programming is combined with other backend
open source available software’s for creation of real time applications. This
unit covers the advance concepts of PHP for better programming skills in
connection of PHP with other languages.
9.1 OBJECTIVE
This unit helps you to
Self-Instructional Material
PHP code almost as seamlessly as you do with HTML. Numerous PHP
Php and Mysql Database
functions work specifically with MySQL to make your life easier.
Some of the more commonly used functions are:
NOTES
mysql_connect([$host[, $username[, $password]]]): Connects to the
MySQL server and returns a resource which is used to reference the
connection.
Self-Instructional Material
Php and Mysql Database For the most part, your specific needs and the way you are designing your
table will dictate what piece of code you use. Most people use the first
method for security ‘sake and put them variables in a different file. Then they
include them wherever they need to make a connection to the database.
NOTES 9.2.2 Web Interface with Apache, MySQL, and PHP
phpMyAdmin is a tool written in PHP intended to handle the administration
of MySQL over the Web. Currently it can create and drop databases,
create/drop/alter tables, delete/edit/add fields, execute any SQL statement,
manage keys on fields. Features provided by the program include:
1. Web interface
2. MySQL database management
3. Import data from CSV and SQL
4. Export data to various formats: CSV, SQL, XML, PDF (via the TCPDF
library), ISO/IEC 26300 - OpenDocument Text and Spreadsheet, Word,
Excel, LaTeX and others PHP in the Web Environment
5. Administering multiple servers
6. Creating PDF graphics of the database layout
7. Creating complex queries using Query-by-example (QBE)
8. Searching globally in a database or a subset of it
9. Transforming stored data into any format using a set of predefined
functions, like displaying BLOB-data as image or download-link
10. Active query monitor (Processes)
AMP Bundles
There are many AMP bundles such as LAMP, XAMP, PHPTriad, WAMP,
MAMP, FoxServ,Etc. consists of AMP build in itself. So, there is no need to
configure AMPs manually. Someof the AMPs which are available for various
operating systems are LAMP (for Linux);WAMP (for Windows); MAMP
(for Macintosh); SAMP (for Solaris); and FAMP (forFreeBSD)
Self-Instructional Material
/usr/local/myapp/docs
Php and Mysql Database
The forwards slash marks each division in the reference, and the sequence is
read from left to right. The equivalent to the fully qualified file reference in
NOTES
LDAP is the "distinguished name", referred to simply as "dn". An example
dn might be:
cn=John Smith,ou=Accounts,o=My Company,c=US
The comma marks each division in the reference, and the sequence is read
from right to left. You would read this dn as:
country = US
organization = My Company
organizationalUnit = Accounts
commonName = John Smith
In the same way as there are no hard rules about how you organise the
directory structure of a hard disk, a directory server manager can set up any
structure that is meaningful for the purpose. However, there are some
conventions that are used. The message is that you cannot write code to
access a directory server unless you know something about its structure, any
more than you can use a database without some knowledge of what is
available.
111
Self-Instructional Material
Php and Mysql Database If this displays a page showing your PHP installation related information then
it means you have PHP and Webserver installed properly. Otherwise you
have to follow given procedure to install PHP on your computer.This section
will guide you to install and configure PHP over the following four platforms
NOTES Apache Configuration
If you are using Apache as a Web Server then this section will guide you to
edit Apache Configuration Files.Just Check it here − PHP Configuration in
Apache Server
Self-Instructional Material
PHP makes use of mail() function to send an email. This function requires
Php and Mysql Database
three mandatory arguments that specify the recipient's email address, the
subject of the message and the actual message additionally there are other
two optional parameters. NOTES
Example
Following example will send an HTML email message to
[email protected] copying it to [email protected]. You can code
this program in such a way that it should receive all content from the user and
then it should send an email.
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
113
Self-Instructional Material
Php and Mysql Database <?php
$to = "[email protected]";
$subject = "This is subject";
NOTES
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:[email protected] \r\n";
$header .= "Cc:[email protected] \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
/body>
</html>
Self-Instructional Material
$fileatt = $attachment; // Path to the file
Php and Mysql Database
$fileatt_type = "application/octet-stream"; // File Type
$start = strrpos($attachment, '/') == -1 ? NOTES
strrpos($attachment, '//') : strrpos($attachment, '/')+1;
$fileatt_name = substr($attachment, $start,
strlen($attachment)); // Filename that will be used for the
file as the attachment
$email_from = $from; // Who the email is from
$subject = "New Attachment Message";
$email_subject = $subject; // The Subject of the email
$email_txt = $message; // Message that the email has in it
$email_to = $to; // Who the email is to
$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$msg_txt="\n\n You have recieved a new attachment message from
$from";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type:
multipart/mixed;\n" . "
boundary=\"{$mime_boundary}\"";
$email_txt .= $msg_txt;
$email_message .= "This is a multi-part message in MIME
format.\n\n" .
"--{$mime_boundary}\n" . "Content-Type:text/html;
charset = \"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" .
$email_txt . "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" . "Content-Type:
{$fileatt_type};\n" .
" name = \"{$fileatt_name}\"\n" . //"Content-Disposition:
attachment;\n" .
//" filename = \"{$fileatt_name}\"\n" . "Content-Transfer-Encoding:
115
Self-Instructional Material
Php and Mysql Database base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";
$ok = mail($email_to, $email_subject, $email_message, $headers);
if($ok) {
NOTES
echo "File Sent Successfully.";
unlink($attachment); // delete a file after attachment sent.
}else {
die("Sorry but the email could not be sent. Please go back and try
again!");
}
}
move_uploaded_file($_FILES["filea"]["tmp_name"],
'temp/'.basename($_FILES['filea']['name']));
mail_attachment("$from", "[email protected]",
"subject", "message", ("temp/".$_FILES["filea"]["name"]));
}
?>
<html>
<head>
<script language = "javascript" type = "text/javascript">
function CheckData45() {
with(document.filepost) {
if(filea.value ! = "") {
document.getElementById('one').innerText =
"Attaching File ... Please Wait";
}
}
}
</script>
</head>
<body>
<table width = "100%" height = "100%" border = "0"
cellpadding = "0" cellspacing = "0">
<tr>
<td align = "center">
116
Self-Instructional Material
<form name = "filepost" method = "post"
Php and Mysql Database
action = "file.php" enctype = "multipart/form-data" id = "file">
<table width = "300" border = "0" cellspacing = "0" NOTES
cellpadding = "0">
<tr valign = "bottom">
<td height = "20">Your Name:</td>
</tr>
<tr>
<td><input name = "from" type = "text"
id = "from" size = "30"></td>
</tr>
<tr valign = "bottom">
<td height = "20">Your Email Address:</td>
</tr>
<tr>
<td class = "frmtxt2"><input name = "emaila"
type = "text" id = "emaila" size = "30"></td>
</tr>
<tr>
<td height = "20" valign = "bottom">Attach File:</td>
</tr>
<tr valign = "bottom">
<td valign = "bottom"><input name = "filea"
type = "file" id = "filea" size = "16"></td>
</tr>
<tr>
<td height = "40" valign = "middle"><input
name="Reset2" type="reset" id ="Reset2" value="Reset">
<input name = "Submit2" type = "submit"
value = "Submit" onClick = "return CheckData45()"></td>
</tr>
</table>
</form>
<center>
117
Self-Instructional Material
Php and Mysql Database <table width = "400">
<tr>
<td id = "one">
NOTES
</td>
</tr>
</table>
</center>
</td>
</tr>
</table>
</body>
</html>
118
Self-Instructional Material
Not Enough Equal Signs − When you ask whether two values are equal in a
Php and Mysql Database
comparison statement, you need two equal signs (==). Using one equal sign
is a common mistake.
NOTES
Misspelled Variable Names − If you misspelled a variable then PHP
understands it as a new variable. Remember: To PHP, $test is not the same
variable as $Test.
Missing Dollar Signs − A missing dollar sign in a variable name is really
hard to see, but at least it usually results in an error message so that you know
where to look for the problem.
Troubling Quotes − You can have too many, too few, or the wrong kind of
quotes. So check for a balanced number of quotes.
Error handling is the process of catching errors raised by your program and
then taking appropriate action. If you would handle errors properly then it
may lead to many unforeseen consequences. It’s very simple in PHP to
handle an errors.
Self-Instructional Material
Php and Mysql Database This way you can write an efficient code. Using above technique you can
stop your program whenever it errors out and display more meaningful and
user friendly message.
Syntax
error_function(error_level,error_message,
error_file,error_line,error_context);
Self-Instructional Material
int error_reporting ( [int $level] )
Php and Mysql Database
Following is the way you can create one error handling function −
<?php NOTES
die();
}
?>
Throw − This is how you trigger an exception. Each "throw" must have at
least one "catch".
Catch − A "catch" block retrieves an exception and creates an object
containing the exception information.
When an exception is thrown, code following the statement will not be
executed, and PHP will attempt to find the first matching catch block. If an
exception is not caught, a PHP Fatal Error will be issued with an "Uncaught
Exception. Exception can be thrown, and caught ("catched") within PHP.
Code may be surrounded in a try block. Each try must have at least one
corresponding catch block. Multiple catch blocks can be used to catch
different classes of exceptions. Exceptions can be thrown (or re-thrown)
within a catch block.
Example
Following is the piece of code, copy and paste this code into a file and verify
the result.
121
Self-Instructional Material
Php and Mysql Database <?php
try {
$error = 'Always throw this error';
NOTES
throw new Exception($error);
// Code following an exception is not executed.
echo 'Never executed';
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo 'Hello World';
?>
In the above example $e->getMessage function is used to get error message.
There are following functions which can be used from Exception class.
getMessage() − message of exception
getCode() − code of exception
getFile() − souce filename
getLine() − source line
getTrace() − n array of the backtrace()
getTraceAsString() − formated string of trace
9.7 TEMPLATES
Many programming instructors emphasize separating content, layout, and
data. However, the way PHP is often written, it combines all three elements.
As a response, web developers often use some form of templating system to
try to separate the content from the view. The simplest form of a template is
something like the following code:
<?php include_once("vars.php") ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
122
Self-Instructional Material
<title><?=$title?></title>
Php and Mysql Database
</head>
<body> NOTES
<h1><?=$heading?></h1>
<div id = "main">
<?=$content?>
</div>
<div id = "footer">
<?=$footer?>
</div>
</body>
</html>
The page holds the structure, but none of the actual contents. The contents are
stored in PHP variables, which are stored in another file, called (in this
example) vars.php. Here’s what vars.php might look like:
<?php
$title = "template demo";
$heading = "Template Demo";
$content = <<<HERE
This is a very simple template example, which allows the user to load content
as variables from an external file. Of course, template systems get much more
complex than this.
HERE;
$footer = "from HTML5 / CSS All in One for Dummies";
?>
In this extremely simple example, the second PHP file simply defines
variables containing the various values, achieving separation of data from
view. Often, the secondary PHP file is more sophisticated, grabbing contents
from a database or other storage medium
123
Self-Instructional Material
Check your Progress
Php and Mysql Database 1. What is PHP?
2. What is LDAP?
3. What are Missing Semicolons?
4. What are Missing Dollar Signs?
5. What are templates?
NOTES
9.8 ANSWERS TO CHECK YOUR PROGRESS
1. Python is the open source programming language which is very easy
and effective among programmers. This unit helps the user to start
from the basic of python in defining their syntax, control and loops
which makes the beginners to learn and understand more easily.
3. Immutable Objects are of in-built types like int, float, bool, string,
unicode, tuple. In simple words, an immutable object can’t be
changed after it is created.
4. A tuple is a sequence of immutable Python objects. Tuples are
sequences, just like lists. The differences between tuples and lists are,
the tuples cannot be changed unlike lists and tuples use parentheses,
whereas lists use square brackets.
5. Python conditional statements are also known as selection
statements.Among multiple options only one statement is selected and
executed is selection statements.Conditional statements in python are
if statement, if-else statements and if elif in python.
9.9 SUMMARY
The open source software PHP programming is combined with other
backend open source available software’s for creation of real time
applications.
phpMyAdmin is a tool written in PHP intended to handle the
administration of MySQL over the Web.
LDAP is the Lightweight Directory Access Protocol, and is a
protocol used to access "Directory Servers".
In order to develop and run PHP Web pages three vital components
need to be installed on our computer system.
Windows users should ensure that two directives are supplied. The
first is called SMTP that defines your email server address. The
second is called send mail from which defines your own email
address.
9.10 KEYWORDS
Error handling: It is the process of catching errors raised by your program
and then taking appropriate action.
124
Self-Instructional Material
Missing Semicolons − Every PHP statement ends with a semicolon (;). PHP
Php and Mysql Database
doesn't stop reading a statement until it reaches a semicolon.
Catch: A "catch" block retrieves an exception and creates an object
containing the exception information. NOTES
125
Self-Instructional Material
Syntax And Style
BLOCK – IV
OPEN SOURCE PROGRAMMING
NOTES LANGUAGE PYTHON
126
Self-Instructional Material
10.9.3 Delete Dictionary Elements
Syntax And Style
10.9.4 Properties of Dictionary Keys
10.9.5 Built-in Dictionary Functions & Methods
10.9.6 Methods
10.10 Control Flow NOTES
10.10.1 if statement
10.10.2 if…else statement
10.10.3 if…elif…else statement
10.10.4 Nested if statement:
10.11 Iteration (Looping Statements)
10.11.1 While statement
10.11.2 Nested while loop
10.11.3 Using else statement with while loops
10.11.4. The Infinite while Loop
10.11.5 for loop
10.11.6 Nested for loop
10.11.7 Using else statement with for loops
10.11.8 for loop using Range
10.11.9 for loop using variable name
10.12 Answers to Check Your Progress
10.13 Summary
10.14 Keywords
10.15 Self Assessment Questions and Exercises
10.16 Further Readings
10.0 INTRODUCTION
Python is the open source programming language which is very easy and
effective among programmers. This unit helps the user to start from the basic
of python in defining their syntax, control and loops which makes the
beginners to learn and understand more easily
10.1 OBJECTIVE
The users after going through this unit can start programming in python by
learning the following concepts
Phython objects
Numbers
Sequences
Strings
Loops
127
Self-Instructional Material
Syntax And Style 10.2 SYNTAX AND STYLE
We learned in the previous page, Python syntax can be executed by writing
directly in the Command Line:
NOTES
>>> print("Hello, World!")
Hello, World!
Or by creating a python file on the server, using the .py file extension, and
running it in the Command Line:
C:\Users\Your Name>python myfile.py
int
float
Int
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
Example
Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
128
Self-Instructional Material
print(type(y))
Syntax And Style
print(type(z))
Float
NOTES
Float, or "floating point number" is a number, positive or negative, containing
one or more decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x) )
print(type(y))
print(type(z))
10.5 SEQUENCE
In Python, sequence is the generic term for an ordered set. There are several
types of sequences in Python, the following three are the most important.
Lists are the most versatile sequence type. The elements of a list can be any
object, and lists are mutable - they can be changed. Elements can be
reassigned or removed, and new elements can be inserted.
129
Self-Instructional Material
Syntax And Style Tuples are like lists, but they are immutable - they can't be changed. Strings
are a special type of sequence that can only store characters, and they have a
special notation. However, all of the sequence operations described below
can also be used on strings.
NOTES 10.6 STRINGS
A string is a sequence of characters.
Strings are the data types in Python.
Python treats single quotes the same as double quotes.
var1 = 'Hello World!'
var2 = "Python Programming"
Simple program
my_string = "Hello“
print(my_string)
Output:
Hello
Program:
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0] )
print( "var2[1:5]: ", var2[1:5])
Output:
var1[0]: H
var2[1:5]: ytho
Program:
str = 'programiz‘
print('str = ', str)
print('str[0] = ', str[0])
print('str[-1] = ', str[-1])
print('str[1:5] = ', str[1:5])
print('str[5:-2] = ', str[5:-2])
Output:
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am
130
Self-Instructional Material
String Built in Function
Syntax And Style
1-lower()
Converts all uppercase letters in string to lowercase.
Syntax:
s.lower()
NOTES
Program:
string = "Hello World"
print (string.lower() )
Output:
Hello world
2-upper()
returns uppercase version of the string
Syntax:
s.upper()
Program:
string = "Hello World"
print (string.upper() )
Output:
HELLO WORLD
3-strip()
returns a string with whitespace removed from the start andend
Syntax:
s.strip()
Program:
string = "Hello World"
print (string.strip() )
Output:
HelloWorld
4-replace('old', 'new')
returns a string where all occurrences of 'old' have been replaced by
'new‘
Syntax:
s.replace()
Program:
string = "Hello World"
print (string.replace(“Hello”,”Welcome”) )
Output:
Welcome World
5-split('delim')
returns a list of substrings separated by the given delimiter.
Syntax:
s.split()
Program:
string = "Hello World"
print (string.split() )
131
Self-Instructional Material
Syntax And Style Output:
['Hello', 'World']
6-join(list)
opposite of split(), joins the elements in the given list together using
NOTES the string as the delimiter.
Syntax:
s.join()
Program:
string = ['Hello', 'World']
print (string.join() )
Output:
"Hello World"
7-capitalize()
Capitalizes first letter of string
Syntax:
s.capitalize()
Program:
string = "hello world"
print (string.capitalize() )
Output:
Hello world
8-len(string)
Returns the length of the string
Syntax:
len(string)
Program:
string = "Hello World"
print (len(string) )
Output:
10
9-isalnum()
Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
Syntax:
s.isalnum()
Program:
string = "Hello World"
print (string.isalnum() )
Output:
False
10-isalpha() -
Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
Syntax:
s.alpha()
132
Self-Instructional Material
Program:
Syntax And Style
string = "Hello World"
print (string.isalpha() )
Output:
True
11-isdigit() NOTES
Returns true if string contains only digits and false otherwise.
Syntax:
s.isdigit()
Program:
string = "Hello World"
print (string.isdigit() )
Output:
False
12-islower()
Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.
Syntax:
s.islower()
Program:
string = "Hello World"
print (string.islower() )
Output:
False
13-isnumeric()
Returns true if a unicode string contains only numeric characters and
false otherwise.
Syntax:
s.isnumeric()
Program:
string = "Hello World"
print (string.isnumeric() )
Output:
False
14-isspace()
Returns true if string contains only whitespace characters and false
otherwise.
Syntax:
s.isspace()
Program:
string = "Hello World"
print (string.isspace() )
Output:
--------------True
15-istitle()
Returns true if string is properly "titlecased" and false otherwise.
133
Self-Instructional Material
Syntax And Style Syntax:
s.istitle()
Program:
string = "Hello World"
print (string.istitle() )
NOTES Output:
------------True
16-isupper()
Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.
Syntax:
s.isupper()
Program:
string = "Hello World"
print (string.isupper() )
Output:
False
String Module
String module is a python script file, which contains several
number of related functions to strings that script is used as module without its
extension(.py) in other python program. This is called string module
Program:
import string #importing srting module
text = "Monty Python's Flying Circus"
print ("upper", "=>", string.upper(text))
print ("lower", "=>", string.lower(text))
print ("split", "=>", string.split(text))
print ("join", "=>", string.join(string.split(text), "+"))
print ("replace", "=>", string.replace(text, "Python", "Java"))
print ("find", "=>", string.find(text, "Python"), string.find(text,
"Java"))
Print("count", "=>", string.count(text, "n"))
Output:
upper => MONTY PYTHON'S FLYING CIRCUS
lower => monty python's flying circus
split => ['Monty', "Python's", 'Flying', 'Circus']
join => Monty+Python's+Flying+Circus
replace => Monty Java's Flying Circus
find => 6 -1
count => 3
Immutability in python:
Mutable vs Immutable Objects in Python
Every variable in python holds an instance of an object. There are two
types of objects in python i.e. Mutable and Immutable objects.
134
Self-Instructional Material
Whenever an object is instantiated, it is assigned a unique object id.
Syntax And Style
The type of the object is defined at the runtime and it can’t be
changed afterwards. However, it’s state can be changed if it is a
mutable object.
mutable objects can change their state or contents and immutable NOTES
objects can’t change their state or content.
Immutable Objects : These are of in-built types like int, float, bool, string,
unicode, tuple. In simple words, an immutable object can’t be changed after it
is created.
Example:
# Python code to test that
# tuples are immutable
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Error :
10.7 LISTS
Lists are the one of data types in python.
A list contains items or elments separated by commas and enclosed
within square brackets ([]).
Lists are similar to arrays in python.
One of the differences between them is that all the items belonging to a
list can be of different data type.
Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
135
Self-Instructional Material
Syntax And Style 10.7.2 List Slices
Accessing List values or (List Slicing)
The values stored in a list can be accessed using the slice operator
[:] with indexes starting at 0 in the beginning of the list and working their
NOTES way to end -1.
Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
print (list) # Prints complete list
print (list[0]) # Prints first element of the list abcd
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
Output:
['abcd', 786, 2.23, 'john', 70.2]
['abcd‘]
[786, 2.23]
[2.23, 'john', 70.2]
Syntax
list.remove(obj)
obj − This is the Object to be removed from the given list.
Example
aList = [123, 'xyz', 'zara', 'abc', ‘kyz'];
aList.remove('xyz');
Print("List : ", aList)
aList.remove('abc');
Print("List : ", aList)
Output:
List : [123, 'zara', 'abc', ‘kyz']
List : [123, 'zara', ‘kyz']
136
Self-Instructional Material
iii) pop() method:
Syntax And Style
The method pop() removes and returns last object or obj from the list.
Syntax
list.pop(obj = list[-1])
obj − This is an optional parameter, index of the object to be
removed from the list. NOTES
Example
aList = [123, 'xyz', 'zara', 'abc'];
print ("A List : ", aList.pop())
print ("B List : ", aList.pop(2))
Output:
A List : abc
B List : zara
Example
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.reverse();
Print("List : ", aList)
Output:
List : ['xyz', 'abc', 'zara', 'xyz', 123]
v) append() method:
The method append() appends a passed obj into the existing list.
Syntax
list.append(obj)
obj − This is the object to be appended in the list.
Example
List = [123, 'xyz', 'zara', 'abc'];
aList.append( 2009 );
Print("Updated List : ", aList)
Output:
Updated List : [123, 'xyz', 'zara', 'abc', 2009]
Syntax
list.extend(seq)
seq − This is the list of elements
Example
aList = [123, 'xyz', 'zara', 'abc', 123];
bList = [2009, 'manni'];
aList.extend(bList)
137
Self-Instructional Material
Syntax And Style print("Extended List : ", aList)
Output:
Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']
Self-Instructional Material
Output
Syntax And Style
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
NOTES
Program
colors = ["red", "green", "blue", "purple"]
i=0
while i < len(colors):
print(colors[i])
i += 1
Output
red
green
blue
purple
Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
print ("Value available at index 2 : " )
print (list[2])
list[2] = 6.5; #List is mutable (because updating is applicable)
print ("New value available at index 2 : " )
print (list[2])
Output:
Value available at index 2 :
2.23
Program
a = [1, 2, 3]
b=a
print (a,b)
139
Self-Instructional Material
Syntax And Style print (id(a), id(b))
Output-
[1, 2, 3],[1, 2, 3]
135023431 135023431
NOTES
More importantly, changing b also changes a
b[0] = 0
print a
[0, 2, 3]
Output:
Old list: [1, 2, 3, 4]
New copied list: [1, 2, 3, 4]
Self-Instructional Material
New copied list: [1, 2, 3, 4]
Syntax And Style
Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
2) max() function:
The method max() returns the elements from the list with maximum
value.
Syntax
max(list)
list - This is a list from which max valued element to be returned.
Example
list1 = [456, 700, 200]
print ("Max value element : ", max(list1))
Output:
Max value element : 700
3) min() function:
The method min() returns the elements from the list with minimum
value.
141
Self-Instructional Material
Syntax And Style Syntax
min(list)
list - This is a list from which min valued element to be returned.
Example
list1 = [456, 700, 200]
NOTES print ("min value element : ", min(list1))
Output:
min value element : 200
Example:
new_list = [ ]
for i in old_list:
if filter(i):
new_list.append(expressions(i))
list comprehension
-It can obtain the same thing using list comprehension:
new_list = [expression(i) for i in old_list if filter(i)]
142
Self-Instructional Material
Syntax And Style
-new_list The new list (result).
-expression(i) Expression is based on the variable used for each
element in the old list.
-for i in old_list The word for followed by the variable name to use,
followed by the word in the old list. NOTES
-if filter(i) Apply a filter with an If-statement.
syntax
[expression for item in list if conditional]
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
143
Self-Instructional Material
Syntax And Style tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a
NOTES comma, even though there is only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
Self-Instructional Material
del tup;
Syntax And Style
print "After deleting tup : ";
print tup;
This produces the following result. Note an exception raised, this is because
after del tup tuple does not exist any more −
('physics', 'chemistry', 1997, 2000) NOTES
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
Self-Instructional Material
Syntax And Style abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2
1. cmp()
The method cmp() compares elements of two tuples.
Syntax
Following is the syntax for cmp() method −
cmp(tuple1, tuple2)
Parameters
tuple1 − This is the first tuple to be compared
tuple2 − This is the second tuple to be compared
Return Value
If elements are of the same type, perform the compare and return the result.
If elements are different types, check to see if they are numbers.
If numbers, perform numeric coercion if necessary and compare.
If either element is a number, then the other element is "larger"
(numbers are "smallest").
Otherwise, types are sorted alphabetically by name.
If we reached the end of one of the tuples, the longer tuple is "larger." If we
exhaust both tuples and share the same data, the result is a tie, meaning that
0 is returned.
Example
tuple1, tuple2 = (123, 'xyz'), (456, 'abc')
print cmp(tuple1, tuple2)
print cmp(tuple2, tuple1)
tuple3 = tuple2 + (786,);
print cmp(tuple2, tuple3)
When we run above program, it produces following result −
-1
1
-1
2. len()
The method len() returns the number of elements in the tuple.
Syntax
len(tuple)
146
Self-Instructional Material
Parameters
Syntax And Style
tuple − This is a tuple for which number of elements to be counted.
Return Value
This method returns the number of elements in the tuple.
Example
The following example shows the usage of len() method. NOTES
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print "First tuple length : ", len(tuple1)
print "Second tuple length : ", len(tuple2)
When we run above program, it produces following result −
First tuple length : 3
Second tuple length : 2
3. max()
The method max() returns the elements from the tuple with maximum value.
Syntax
Following is the syntax for max() method −
max(tuple)
Parameters
tuple − This is a tuple from which max valued element to be returned.
Return Value
This method returns the elements from the tuple with maximum value.
Example
The following example shows the usage of max() method.
tuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700, 200)
print "Max value element : ", max(tuple1)
print "Max value element : ", max(tuple2)
When we run above program, it produces following result −
Max value element : zara
Max value element : 700
4. min()
The method min() returns the elements from the tuple with minimum value.
Syntax
Following is the syntax for min() method −
min(tuple)
Parameters
tuple − This is a tuple from which min valued element to be returned.
Return Value
This method returns the elements from the tuple with minimum value.
Example
The following example shows the usage of min() method.
tuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700,
200)
print "min value element : ", min(tuple1)
print "min value element : ", min(tuple2)
When we run above program, it produces following result −
min value element : 123
min value element : 200
elf-Instructional 5. tuple()
aterial
147
Self-Instructional Material
Syntax And Style Description
The method tuple() converts a list of items into tuples
Syntax
Following is the syntax for tuple() method −
tuple( seq )
NOTES Parameters
seq − This is a sequence to be converted into tuple.
Return Value
This method returns the tuple.
Example
The following example shows the usage of tuple() method.
aList = [123, 'xyz', 'zara', 'abc']
aTuple = tuple(aList)
print "Tuple elements : ", aTuple
When we run above program, it produces following result −
Tuple elements : (123, 'xyz', 'zara', 'abc')
10.9 DICTIONARY
Python dictionary is an unordered collection of items.
While other compound data types have only value as an element, a dictionary
has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.
• Creating a dictionary is as simple as placing items inside curly braces
{} separated by comma.
• An item has a key and the corresponding value expressed as a pair,
key: value.
• Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces.
An empty dictionary without any items is written with just two curly
braces, like this: {}.
• Keys are unique within a dictionary while values may not be. The
values of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples.
148
Self-Instructional Material
10.9.2 Updating Dictionary Syntax And Style
You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown below in
the simple example −
Program NOTES
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8;
# update existing entry
dict['School'] = "DPS School";
# Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
Output
dict['Age']: 8
dict['School']: DPS School
Program
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'];
# remove entry with key 'Name'
dict.clear();
# remove all entries in dict
del dict ;
# delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
Output
Error undefined
149
Self-Instructional Material
Syntax And Style For example
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result −
NOTES dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or
tuples as dictionary keys but something like ['key'] is not allowed.
Following is a simple example
dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'
2.str()
Produces a printable string representation of a dictionary
Syntax:
Str(variable name)
Program:
dict = {'Name': 'Zara', 'Age': 7};
print "Equivalent String : %s" % str (dict)
Output:
Equivalent String : {'Age': 7, 'Name': 'Zara'}
3. type()
Returns the type of the passed variable. If passed variable is
dictionary, then it would return a dictionary type.
Syntax:
type(variable name)
Program:
dict = {'Name': 'Zara', 'Age': 7};
print "Variable Type : %s" % type (dict)
150
Self-Instructional Material
Output:
Syntax And Style
Variable Type : <type 'dict'>
4. cmp()
The method cmp() compares two dictionaries based on key and values.
Syntax NOTES
Return Value
This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2 and 1
if dict1 > dic2.
Example
The following example shows the usage of cmp() method.
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = {'Name': 'Mahnaz', 'Age': 27};
dict3 = {'Name': 'Abid', 'Age': 27};
dict4 = {'Name': 'Zara', 'Age': 7};
print "Return Value : %d" % cmp (dict1, dict2)
print "Return Value : %d" % cmp (dict2, dict3)
print "Return Value : %d" % cmp (dict1, dict4)
When we run above program, it produces following result −
Return Value : -1
Return Value : 1
Return Value : 0
10.9.6 Methods
1.clear()
Removes all elements of dictionary dict
Syntax:
dict.clear()
Program:
dict = {'Name': 'Zara', 'Age': 7};
print "Start Len : %d" % len(dict)
dict.clear()
print "End Len : %d" % len(dict)
Output:
Start Len : 2
End Len : 0
2.copy()
Returns a shallow copy of dictionary dict
151
Self-Instructional Material
Syntax And Style Syntax:
dict.copy()
Program:
NOTES
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print "New Dictionary : %s" % str(dict2)
Output:
New Dictionary : {'Age': 7, 'Name': 'Zara'}
3.fromKeys()
Create a new dictionary with keys from seq and values set to value
Syntax:
dict.fromkeys()
Program:
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print "New Dictionary : %s" % str(dict)
dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" % str(dict)
Output:
New Dictionary : {'age': None, 'name': None, 'sex': None} New
Dictionary : {'age': 10, 'name': 10, 'sex': 10}
4.get(key, default=None)
For key key, returns value or default if key not in dictionary
Syntax:
dict.get(key,default=None)
Program:
dict = {'Name': 'Zabra', 'Age': 7}
print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Education', "Never")
Output:
Value : 7 Value : Never
5.has_key(key)
Returns true if key in dictionary dict, false otherwise
Syntax:
dict.has_key()
Program:
152
Self-Instructional Material
dict = {'Name': 'Zara', 'Age': 7}
Syntax And Style
print "Value : %s" % dict.has_key('Age')
print "Value : %s" % dict.has_key('Sex')
Output:
Value : True NOTES
Value : False
6.items()
Returns a list of dict's (key, value) tuple pairs
Syntax:
dict.items()
Program:
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.items()
output:
Value:[('Name': 'Zara'), ('Age': 7)]
7.keys()
Returns list of dictionary dict's keys
Syntax:
dict.keys()
Program:
dict={'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.items()
output:
Value:[‘Name’,’Age’]
8.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already
in dict
Syntax:
dict.setdefault()
Program:
dict={'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.setdefault(‘Age’,None)
print "Value : %s" % dict.setdefault(‘Sex’,None)
output:
Value:7
Value:None
9.update(dict2)
153
Self-Instructional Material
Syntax And Style Adds dictionary dict2's key-values pairs to dict
Syntax:
dict.update(new dict)
Program:
dict={'Name': 'Zara', 'Age': 7}
NOTES dict2={‘Sex’:’female’}
dict.update(dict2)
print "Value : %s" % dict
output:
Value: {'Name': 'Zara', 'Age': 7, ‘Sex’:’female’}
10.values()
Returns list of dictionary dict's values
Syntax:
dict.values()
Program:
dict={'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.values()
output:
Value:[7,’Zara’]
154
Self-Instructional Material
Python Transfer statements
Syntax And Style
Transfer statements in python are the statements which are used to
transfer execution to other statements.
Python transfer statements are break statement, continue statement
and pass statement.
NOTES
Decision making statements (Conditional)
Decision making constructs with Boolean expression, an expression returns
either TRUE or FALSE
(i.e., 0-false and 1-true). Decision making structure is to perform an action or
a calculation only when a certain condition is met. There are four types of
decision making structure. They are,
1. if statement (Conditional statement)
2. if … else statement (Alternative statement)
3. elif statement (Chained condition)
4. nested if statement
10.10.1 if statement
The program evaluates the condition and will execute statement(s) or
process only if the test expression is True.
Syntax:
if (test expression/condition):
True statement
Program:
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
Output:
3 is a positive number
This is always printed
Self-Instructional Material
Syntax And Style 10.10.3 if…elif…else statement
The elif is short for else if. It allows us to check for multiple
expressions. If the condition for if is False, it checks the condition of the
next elif block and so on. If all the conditions are False, body of else is
NOTES executed.
Syntax:
if (test expression/condition):
True statement 1
elif (test expression/condition):
True statement 2
else:
False statement
Program:
num=3
if num > 0:
print("Positive number")
elif num = = 0:
print("Zero")
else:
print("Negative number")
Output:
Positive number
156
Self-Instructional Material
10.11 ITERATION (LOOPING STATEMENTS): Syntax And Style
(Looping/ Repetition statement)
Loop statement is to execute a specific block of code in multiple numbers
of times. A loop is a programming control structure that facilitates the
repetition execution of a statement or group of statement. There are two types NOTES
of loop statement. They are,
1. while loop
2. for loop
157
Self-Instructional Material
Syntax And Style The count is:4
Good bye!
158
Self-Instructional Material
10.11.6 Nested for Loop Syntax And Style
Nesting defined as the placing of one for loop inside the body of
another for loop.
Syntax: NOTES
for variableName in <Group of numbers>:
for variableName in <Group of numbers>:
body of loop
Program:
S=0
for i in range(3):
for j in range(3):
S=i+j
Print(s)
print(“end”)
Output:
0
2
4
end
159
Self-Instructional Material
Syntax And Style 1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
NOTES
How to use range:
range(10) #produces the list: [0,1,2,3,4,5,6,7,8,9]
range(1, 7) #produces the list: [1,2,3,4,5,6]
range(0, 30, 5) #produces the list: [0,5,10,15,20,25]
range(5, -1, -1) #produces the list: [5,4,3,2,1,0]
Self-Instructional 160
Material
Self-Instructional Material
Syntax And Style
10.12 ANSWERS TO CHECK YOUR PROGRESS
1. Python is the open source programming language which is very easy
and effective among programmers. This unit helps the user to start
NOTES
from the basic of python in defining their syntax, control and loops
which makes the beginners to learn and understand more easily.
3. Immutable Objects are of in-built types like int, float, bool, string,
unicode, tuple. In simple words, an immutable object can’t be
changed after it is created.
4. A tuple is a sequence of immutable Python objects. Tuples are
sequences, just like lists. The differences between tuples and lists are,
the tuples cannot be changed unlike lists and tuples use parentheses,
whereas lists use square brackets.
5. Python conditional statements are also known as selection
statements.Among multiple options only one statement is selected and
executed is selection statements.Conditional statements in python are
if statement, if-else statements and if elif in python.
10.13 SUMMARY
In Python, sequence is the generic term for an ordered set. There are
several types of sequences in Python, the following three are the most
important.
Dictionary values have no restrictions. They can be any arbitrary
Python object, either standard objects or user-defined objects.
However, same is not true for the keys.
In python, flow control is divided into three types which are as
follows: Conditional statements, Iterative statements and Transfer
statements.
In python, flow control is divided into three types which are as
follows: Conditional statements, Iterative statements and Transfer
statements.
Every variable in python holds an instance of an object. There are two
types of objects in python i.e. Mutable and Immutable objects.
10.14 KEYWORDS
Deleting List values: To remove a list element, the del statement can be used
if the element(s) that we want to delete is known exactly or the remove()
method
161
Self-Instructional Material
Syntax And Style Tuples: They are like lists, but they are immutable - they can't be changed.
Strings are a special type of sequence that can only store characters, and they
have a special notation.
String module: String module is a python script file, which contains several
NOTES number of related functions to strings that script is used as module without its
extension(.py) in other python program.
162
Self-Instructional Material
Files
UNIT- 11 FILES
Structure NOTES
11.0 Introduction
11.1 Objective
11.2 Files
11.2.1 Types of File
11.2.1.1 Text File
11.2.1.2 Binary File
11.3 File Modes
11.3.1 File Object Attributes
11.3.2 Opening and Closing a File
11.3.3 Reading and Writing a File
11.3.4 The append()
11.3.5 File Positions
11.4 Errors and Exceptions
11.4.1 Errors
11.4.2 Parts in an Error Message
11.4.3 Built-In Exceptions
11.4.4 Exceptions
11.4.5 Error Messages that are Displayed for the Following
Exceptions
11.5 Handling an Exception
11.5.1 except Clause with No Exceptions
11.5.2 Handling Multiple Exceptions
11.5.3 The except Clause with Multiple Exceptions
11.5.4 Handling an Exception by Try/Except/Else Clause
11.5.5 Handling an Exception by Try/Except/Finally Clause
11.5.6 Raising an Exceptions
11.5.7 User-Defined Exceptions
11.6 Functions
11.7 Parameters
11.8 Arguments
11.9 Fruitful Function
11.10 Variable Scope and Lifetime
11.11 Function Recursion
11.12 Modules and Packages
11.12.1 Modules
11.12.1.1 The import Statement
163
Self-Instructional Material
Files 11.12.1.2 Standard Modules
11.13 Classes and OOP
11.13.1 Defining a Class in Python
11.14 Execution Environment
NOTES 11.15 Answers to Check Your Progress
11.16 Summary
11.17 Keywords
11.18 Self Assessment Questions and Exercises
11.19 Further Readings
11.0 INTRODUCTION
The exception handling and File handling in Python helps the users to
understand and work with programming language more efficiently. This unit
explains the concepts of Exception handling and file handling with example
programs of how it can be implemented and used in real time.
11.1 OBJECTIVE
This unit helps the user to learn and understand
Functions in Python
Files
Exception Handling
Classes and OOp
Exceution Environment
11.2 FILES
File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data
when computer is turned off, we use files for future use of the data.
In Python, there is no need for importing external library to read and
write files. Python provides an inbuilt function for creating, writing
and reading files.
Hence, in Python, a file operation takes place in the following order.
Open a file
Read or write (perform operation)
Close the file
Self-Instructional Material
It is a sequence of characters stored on a permanent medium like a
Files
hard drive, flash memory, or CD-ROM
A text file is a file that contains printable characters and whitespace,
organized in to lines separated by newline characters
Each line is terminated with a special character, called the EOL NOTES
or End of Line character.
There are several types, but the most common is the comma {,} or
newline character. It ends the current line and tells the interpreter a
new one has begun.
r
1. Opens a file for reading only in text format. The file pointer is
placed at the beginning of the file. This is the default mode.
rb
2. Opens a file for reading only in binary format. The file pointer
is placed at the beginning of the file. This is the default mode.
r+
3. Opens a file for both reading and writing. The file pointer
placed at the beginning of the file.
rb+
4. Opens a file for both reading and writing in binary format.
The file pointer placed at the beginning of the file.
w
5. Opens a file for writing only. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.
wb
Opens a file for writing only in binary format. Overwrites the
6.
file if the file exists. If the file does not exist, creates a new
file for writing.
w+
Opens a file for both writing and reading. Overwrites the
7.
existing file if the file exists. If the file does not exist, creates
a new file for reading and writing.
165
Self-Instructional Material
Files wb+
Opens a file for both writing and reading in binary format.
8.
Overwrites the existing file if the file exists. If the file does
not exist, creates a new file for reading and writing.
NOTES a
Opens a file for appending. The file pointer is at the end of
9. the file if the file exists. That is, the file is in the append
mode. If the file does not exist, it creates a new file for
writing.
ab
Opens a file for appending in binary format. The file pointer
10. is at the end of the file if the file exists. That is, the file is in
the append mode. If the file does not exist, it creates a new
file for writing.
a+
Opens a file for both appending and reading. The file pointer
11. is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file
for reading and writing.
ab+
Opens a file for both appending and reading in binary format.
12. The file pointer is at the end of the file if the file exists. The
file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
file.closed
1 Returns true if file is closed, false otherwise.
file.mode
2 Returns access mode with which file was opened.
file.name
3 Returns name of the file.
Self-Instructional Material
Syntax:
Files
o file object = open(file_name [, access_mode][, buffering])
Here are parameter details −
file_name – The file_name argument is a string value that contains the
name of the file that you want to access. NOTES
access_mode – The access_mode determines the mode in which the
file has to be opened, i.e., read, write, append, etc. Default file access
mode is read (r).
buffering − If the buffering value is set to 0, no buffering takes place.
If the buffering value is 1, line buffering is performed while accessing
a file.
ExamplePrgram:
# Open a file
fo = open(“days.txt", “r")
print ("Name of the file: ", fo.name)
print ("Closed or not : ", fo.closed)
print ("Opening mode : ", fo.mode)
fo.close()
Output:
Name of the file: file1.txt
Closed or not : False
Opening mode : r
The close ()
The close() method of a file object flushes any unwritten information and
closes the file object, after which no more writing can be done.
Syntax: fileObject.close();
Program:
# Open a file
fo = open("file1.txt", “r")
print ("Name of the file: ", fo.name)
# Close opened file
fo.close()
print ("Closed or not : ", fo.closed)
Output:
Name of the file: file1.txt
Closed or not : True
days.txt
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
167
Self-Instructional Material
Files 11.3.3 Reading and writing a file
The read() Method
To read a file in Python, we must open the file in reading mode.
The code for opening myfile.txt for input:
NOTES >>>ƒfƒ=ƒopen(“myfile.txt”,ƒ'r')
Syntax:fileObject.read(size);
There are various methods available for this purpose. We can use
the read(size) method to read in size number of data. If size parameter is not
specified, it reads and returns up to the end of the file.
Program:
# Open a file
fo = open(“days.txt", "r")
str1= fo.read(7)
str2 = fo.read()
print ("String is : ", str1)
print ("String is : ", str2)
# Close opened file
fo.close()
Output:
String is : Monday
String is : ‘Tuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday\n’
Program:
# Open a file
fo = open(“days.txt", "r")
print(fo.readline())
print(fo.readline(3))
Output:
Monday
Tuesday
Program:
# Open a file
fo = open(“days.txt", "r")
fl =fo.readlines()
for x in fl:
print x
168
Self-Instructional Material
Output:
Files
Monday
Tuesday
Wednesday
Thursday NOTES
Friday
Saturday
Sunday
Program 1:
# Open a file
fo = open("file1.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
# Closeopened file
fo.close()
Output: file1.txt contains
Python is a great language.
Yeah its great!!
Program 2:
Fivehundred random integers between 1 and 500 are generated and written to
a text file named integers.txt. The newline character is the separator.
importƒrandom
fƒ=ƒopen(“integers.txt”,ƒ'w')
forƒcountƒinƒrange(500):
ƒƒƒƒnumberƒ=ƒrandom.randint(1,ƒ500)
ƒƒƒƒf.write(str(number)ƒ+ƒ“\n”)
f.close()
169
Self-Instructional Material
Files
The writelines() Method
The method writelines() writes a sequence of strings to the file. The
sequence can be any iterable object producing strings, typically a list of
strings. There is no return value.
NOTES Syntax
Following is the syntax for writelines() method −
fileObject.writelines( sequence )
Parameters
sequence − This is the Sequence of the strings.
Return Value
This method does not return any value.
Example
The following example shows the usage of writelines() method.
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
# Open a file in witre mode
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
Program :
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
line = fo.next()
print "Line No %d - %s" % (index, line)
# Close opend file
fo.close()
Output:
Name of the file: foo.txt
Line No 0 - This is 1st line
Line No 1 - This is 2nd line
Line No 2 - This is 3rd line
Line No 3 - This is 4th line
170
Self-Instructional Material
Line No 4 - This is 5th line
Files
Line No 5 - This is 6th line
Line No 6 - This is 7th line
Program 1:
# Open a file
fo = open("file1.txt", “a")
fo.write(“Python is interpreted language")
# Close opend file
fo.close()
Output: file1.txt contains
Python is a great language.
Yeah its great!!
Python is interpreted language
Program 2:
fo = open("test10.txt", "w+")
fo.write( "Python is a great language.\nYeah its great!!\n")
fo.close()
fo = open("test10.txt", "r")
print(fo.readline())
fo.close()
Output
Python is a great language
Program 3:
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
print(program_name)
print(sys.argv[2]
print(count)
Output: python filename.py 5 8
filename.py
8
2
Self-Instructional Material
Files Following is the syntax for tell() method
fileObject.tell()
Return Value
NOTES This method returns the current position of the file read/write pointer
within the file.
Example
The following example shows the usage of tell() method.
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
Program:
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print "Read Line: %s" % (line)
# Get the current position of the file.
pos = fo.tell()
print "Current Position: %d" % (pos)
# Close opend file
fo.close()
Output:
Name of the file: foo.txt
Read Line: Python is a great language.
Current Position: 28
Seek() Method
The method seek() sets the file's current position at the offset. The
whence argument is optional and defaults to 0, which means absolute file
positioning, other values are 1 which means seek relative to the current
position and 2 means seek relative to the file's end.
There is no return value. Note that if the file is opened for appending
using either 'a' or 'a+', any seek() operations will be undone at the next write.
If the file is only opened for writing in append mode using 'a', this
method is essentially a no-op, but it remains useful for files opened in
append mode with reading enabled (mode 'a+').
172
Self-Instructional Material
If the file is opened in text mode using 't', only offsets returned by
Files
tell() are legal. Use of other offsets causes undefined behavior.
Note that not all file objects are seekable.
Syntax NOTES
Following is the syntax for seek() method −
fileObject.seek(offset[, whence])
Parameters
offset − This is the position of the read/write pointer within the file.
whence − This is optional and defaults to 0 which means absolute file
positioning, other values are 1 which means seek relative to the
current position and 2 means seek relative to the file's end.
Return Value
This method does not return any value.
Example
The following example shows the usage of seek() method.
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
Program:
line = fo.readline()
print "Read Line: %s" % (line)
Output:
Name of the file: foo.txt
Read Line: Python is a great language.
Self-Instructional Material
Files Syntax errors are mistakes in the use of the Python language, and are
analogous to spelling or grammar mistakes in a language like English: for
example, the sentence Would you some tea? does not make sense – it is
missing a verb.
Common Python syntax errors include:
NOTES leaving out a keyword
putting a keyword in the wrong place
leaving out a symbol, such as a colon, comma or brackets
misspelling a keyword
incorrect indentation
empty block
Some examples of syntax errors in Python:
• myfunction(x, y):
return x + y
• else:
print("Hello!")
• if mark >= 50
print("You passed!")
• if arriving:
print("Hi!")
• esle:
print("Bye!")
• if flag:
print("Flag is set!")
2. Runtime errors
If a program is syntactically correct – that is, free of syntax errors – it will be
run by the Python interpreter. However, the program may exit unexpectedly
during execution if it encounters a runtime error – a problem which was not
detected when the program was parsed, but is only revealed when a particular
line is executed.
Examples of Python runtime errors:
division by zero
performing an operation on incompatible types
using an identifier which has not been defined
accessing a list element, dictionary value or object attribute which
doesn’t exist
trying to access a file which doesn’t exist
3. Logical errors
Logical errors are the most difficult to fix. They occur when the program runs
without crashing, but produces an incorrect result. The error is caused by a
mistake in the program’s logic.
Some examples of mistakes which lead to logical errors:
using the wrong variable name
indenting a block to the wrong level
using integer division instead of floating-point division
getting operator precedence wrong
making a mistake in a boolean expression
174
Self-Instructional Material
off-by-one, and other numerical errors
Files
Self-Instructional Material
Files Base class for all lookup errors.
15 IndexError
Raised when an index is not found in a sequence.
16 KeyError
Raised when the specified key is not found in the dictionary.
NOTES
17 NameError
Raised when an identifier is not found in the local or global
namespace.
18 UnboundLocalError
Raised when trying to access a local variable in a function or
method but no value has been assigned to it.
19 EnvironmentError
Base class for all exceptions that occur outside the Python
environment.
20 IOError
Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
does not exist.
21 IOError
Raised for operating system-related errors.
22 SyntaxError
Raised when there is an error in Python syntax.
23 IndentationError
Raised when indentation is not specified properly.
24 SystemError
Raised when the interpreter finds an internal problem, but when
this error is encountered the Python interpreter does not exit.
25 SystemExit
Raised when Python interpreter is quit by using the sys.exit()
function. If not handled in the code, causes the interpreter to exit.
26 TypeError
Raised when an operation or function is attempted that is invalid
for the specified data type.
27 ValueError
Raised when the built-in function for a data type has the valid
type of arguments, but the arguments have invalid values
specified.
28 RuntimeError
Raised when a generated error does not fall into any category.
29 NotImplementedError
Raised when an abstract method that needs to be implemented in
an inherited class is not actually implemented.
176
Self-Instructional Material
11.4.4 Exceptions Files
• An exception is an error that happens during execution of a program.
When that error occurs, Python generate an exception that can be
handled, which avoids the program to crash.
• An exception is an event, which occurs during the execution of a NOTES
program that disrupts the normal flow of the program's instructions.
• An exception is a Python object that represents an error.
• Whenever a runtime error occurs, it creates an exception. The
program stops execution and
prints an error message. For example, dividing by zero creates an
exception:
For example
print 55/0
ZeroDivisionError: integer division or modulo
• When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates and quits.
• Program without handling an exception:
a = 10
b=0
result = a/b
print (result)
• The above code cause zero division error that disrupts the normal
flow of the program's instructions
Self-Instructional Material
Files
NOTES
Fig 1:Exception Handling
178
Self-Instructional Material
Program with handling an exception:
Files
a = 10
b = int(input(“Please enter the integer greater than:”))
try:
result = a/b NOTES
print (result)
except ZeroDivisionError:
print (“Error, you have entered zero”)
Output 1:
Please enter the integer greater than 0: 5
2.0
Output 1:
Please enter the integer greater than 0: 0
Error, you have entered zero
In the above program, the string value is given as inputs then it produce a
ValueError exception.
Program 1:
This example opens a file, writes content in the, file and comes out because
there is no problem at all:
Output:
Program 2:
This example tries to open a file where you do not have write permission, so
it raises an exception –
Output:
179
Self-Instructional Material
Files
Output:
180
Self-Instructional Material
result = a/b
Files
print (result)
exceptZeroDivisionError:
print (“Error, you have entered zero”)
exceptValueError: NOTES
print (“Error, Inappropriate value”)
Output:
Please enter the integer greater than 0: a
Error, Inappropriate value
Output:
Please enter the integer greater than 0: a
Error, you have entered zero or inappropriate value
181
Self-Instructional Material
Files 11.5.5 Handling an Exception by try/except/finally clause
finallyclause is mainly used to close the resources. It must be executed even
though exception has been raised.
Example:
>>> raise MemoryError
Traceback (most recent call last):
...
MemoryError
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument
>>> try:
a = int(input("Enter a positive integer value: "))
182
Self-Instructional Material
if a <= 0:
Files
raiseValueError("This is not a positive number!!")
exceptValueError as ve:
print(ve)
NOTES
Output:
If we enter a negative number:
Enter a positive integer: –5
This is not a positive number!!
• The sole argument to raise indicates the exception to be raised. This must
be either an exception instance or an exception class (a class that derives
from Exception).
• If an exception class is passed, it will be implicitly instantiated by calling
its constructor with no arguments:
raiseValueError
It is the shorthand for 'raise ValueError()'
A simpler form of the raise statement allows you to re-raise the exception is
given below:
>>>
>>> try:
... raiseNameError('HiThere')
... exceptNameError:
... print('An exception flew by!')
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: HiThere
Program 1:
183
Self-Instructional Material
Files
Output:
NOTES
Program 1:
Creating a user defined exception class which throws an exception when
age is less than 18.
classMyErrorException(Exception):
def _str_(self):
returnrepr(str(self.errCode) + “ ” + self.errMessage)
age = int(input(“Enter the age:”)
try:
if(age < 18):
raiseMyErrorException(age, “ is less than 18”)
exceptMyErrorException as exp:
print(exp)
print(“Unauthorized for voting”)
Ouput:
Enter the age: 7
7 is less than 18
Unauthorized for voting
Explanation:
• MyErrorException class is a user defined exception which inherits
the properties from Exception class.
• It overrite the str() function to display the user defined error message.
• If the age value is given less than 18, then it raisean user defined
exception calledMyErrorException.
• Once MyErrorException is raised, it needs to be handled in except
clause to display the related error message.
184
Self-Instructional Material
Files
11.6 FUNCTIONS
A function is a block of organized and reusable program code that
NOTES
performs a single, specific and well-defined task. It is a group of statements
that perform a specific task.
Needs for function:
If a program is large, it is difficult to understand the steps involved in it.
Hence, it is subdivided into a number of small program called
subprogram or modules.
Each subprogram specifies one or more actions to be performed for the
larger program. Such subprograms are called as functions.
Advantage of function:
Reduce the program development time and code.
It ensures code readability.
The function can be reused with or without modification when it is
needed.
Why use function?
Maximizing code reuse and minimizing redundancy.
Procedural decomposition.
Types of function:
There are two types of function. They are,
1. Built-in/ pre-defined function – function that are built into python.
2. User defined function – functions defined by user.
Built-in function:
The python interpreter has a number of functions that are always
available for use. These functions are called Built-in functions.
Built-in Description
function
input() Read a line from input, convert it to a string.
print() Print objects to the stream.
len() Return the length of an object.
abs(n) Return absolute value of a number.
pow(n,d) Return n raised to the power d.
sqrt(n) Returns the square root of number.
int() Convert string, floating point into integer data type.
float() Convert string, integer into floating point data type.
str() Convert floating point, integer, list, tuple, and dictionary
into string data type.
list() Convert string, tuple, and dictionary into list data type.
tuples() Convert string and list into tuple data type.
Table 1: Python built-in function
Program:
n=int(input(“enter the number”))
185
Self-Instructional Material
Files print(“the square root of a number: ”,sqrt(n))
Output:
Enter the number: 4
The square root of a number: 16
NOTES
User defined function:
The functions defined by the users according to their requirements are
called user defined function. The user can modify the function according to
their requirements.
Function definition:
The functions are created by user in their programs using the def
keyword. The important points for creating a function as follows as,
Functions blocks starts with the keyword def.
The def keyword followed by function name and parentheses “( ) “.
After the parentheses a colon ( : ) is placed.
Parameter or arguments that the function accepts are placed within
parentheses.
Return statement is optional
The function definition includes two parts:
1. Function header – it begins with keyword def and ends with colon (:)
2. Function body – it consisting of one or more python statements and it
is indented.
Syntax:
def functionName(variable1,variable2,….) :
“””docstring”””
block of statements
return [expression]
Return statements:
A function may or may not return a value. The return statement is
used for two things:
1. Return a value to the called function.
2. To end and exit a function and go back to the called function.
Syntax: return [expression]
186
Self-Instructional Material
The expression is optional. If the expression is presented, it is
Files
evaluated and resultant value is return to the calling function. If no expression
is specified then the function will return none.
Program:
def add(a,b): NOTES
sum=a+b
return sum
a=5
b=4
c=add(a,b)
print(“sum:”,c)
Output:
Sum: 9
11.7 PARAMETERS
The variables that are passed to the function in function definition are
called parameters.
Pass by value: (call by value)
Pass by reference: (call by reference)
Pass by Value:
The most common strategy is the call-by-value evaluation, sometimes also
called pass-by-value. In call-by-value, the argument expression is evaluated,
and the result of this evaluation is bound to the corresponding variable in the
function. So, if the expression is a variable, a local copy of its value will be
used, i.e. the variable in the caller's scope will be unchanged when the
function returns.
def change(x):
x=x+1
print('Inside change function x = ', x)
x=10
187
Self-Instructional Material
Files change(x)
print('Outside change function x = ', x)
Output:
Inside change function x = 11
NOTES Outside change function x = 10
Pass by Reference:
In call-by-reference evaluation, which is also known as pass-by-reference, a
function gets an implicit reference to the argument, rather than a copy of its
value. As a consequence, the function can modify the argument, i.e. the value
of the variable in the caller's scope can be changed.
def changeme( mylist ):
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
Output:
Values inside the function before change: [10, 20, 30]
Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
11.8 ARGUMENTS
When the function with parameters is called, the values that are passed to the
calling function are called arguments.
Function with arguments
Function without arguments
Function arguments:
There are four types of formal arguments. They are:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required arguments:
The arguments are passed to a function in correct positional order.
The number of arguments in the function call should exactly match with the
number of arguments specified in the function definition.
Syntax:
def functionName(variable1,variable2,….) :
block of statements
return [expression]
Program 1:
def display( name, age, salary):
188
Self-Instructional Material
print(“name = ”, name)
Files
print (“age = ", age)
print(“salary = ”,salary)
display(“abc”, 20, 3000)
Output: NOTES
Name = abc
Age = 20
Salary = 3000
Program 2:
def display( name, age, salary):
print(“name = ”, name)
print (“age = ", age)
print(“salary = ”,salary)
display(“abc”, 20)
Output:
Error: required argument value
display(“abc”, 20)
^
2. Keyword arguments:
The values are assigned to the argument based on their position. By
using keyword argument, the order (position) of the argument can be
changed. The values are not assigned to arguments according to their position
but based on their name (keyword).
Syntax:
functionName(variable1 = value1, variable2 = value2)
Program:
def display( name, age, salary):
print(“name = ”, name)
print (“age = ", age)
print(“salary = ”,salary)
display(age = 20, salary = 3000, name = “abc”)
Output:
Name = abc
Age = 20
Salary = 3000
3. Default arguments:
The default value is assigned to the function argument. The default
value to an argument is provided by using the assignment operator (=).
Syntax:
def functionName(variable1,variable2 = value) :
block of statements
return [expression]
189
Self-Instructional Material
Files Program:
def display( name, age, salary = 4000):
print(“name = ”, name)
print (“age = ", age)
print(“salary = ”,salary)
NOTES display(“abc”, 20)
display(“abc”, 20, 5000)
Output:
Name = abc
Age = 20
Salary = 4000
Name = abc
Age = 20
Salary = 5000
Program:
def display( * var):
print(“list = ”, var)
display(“abc”, 20, 3000)
Output:
list = [abc, 20, 4000]
Function composition:
Function composition is a way of combining function such that the
result of each function is passed as the argument of the next function. It is
ability to call function from within another function.
Example:
def f():
return g()
def g( ):
print(“inner function”)
f()
190
Self-Instructional Material
11.9 FRUITFUL FUNCTION: (FUNCTION RETURNING Files
VALUES)
The function which returns values is called the fruitful function. The
statement return [expression] exits in a function pass back an expression to
NOTES
the called function. A return statement with no arguments is return None
value.
Program:
def sum( a, b):
total = a + b
print (“Inside the function : ", total )
return total
c = sum( 10, 20 )
print (“outside the function : ", c )
Output:
Inside the function: 30
Outside the function: 30
Void function:
The function without return statement is called the void function.
Program:
def sum( a, b):
total = a+b
print (“Inside the function : ", total )
sum( 10, 20 )
Output:
Inside the function: 30
Flow of execution:
Before using the function, it is important to define it. To define a
function, we must know the sequence in which the statement of function
should run. This order of statement execution is called as flow of execution.
How function works:
Once a function is called, it takes some data from the calling function
and returns back some value to the called function.
Whenever function is called, control passes to the called function and
working of the calling function is temporarily stopped, when the
execution of the called function is completed then control returns back
to the calling function and execute the next statements.
The function operates on formal and actual arguments and sends back
the result to the calling function using return statement.
191
Self-Instructional Material
Files
NOTES
Output:
the global variable num=10
the local variable num2=20
the local variable num3=30
Accessing global variable num=10
192
Self-Instructional Material
Program:
Files
num=10 #num = global variable
print(“the global variable num=”, num)
def func(num2): #num2 = local variable
print(“the local variable num2=”, num2)) NOTES
global num3=30 #num3 = global variable
print(“the global variable num3=”, num3))
func(20)
print(“Accessing global variable num=”, num)
print(“Accessing global variable num3=”, num3)
Output:
the global variable num=10
the local variable num2=20
the global variable num3=30
Accessing global variable num=10
Accessing global variable num3=10
193
Self-Instructional Material
Files Program:
a=10
sum = lambda a : a + 5
print(“sum = ”,sum)
Output:
NOTES Sum = 15
Self-Instructional Material
#!/usr/bin/python3
Files
# Fibonacci numbers module
def fib(n): # return Fibonacci series up to n
result = [ ]
a, b = 0, 1 NOTES
while b < n:
result.append(b)
a, b = b, a+b
return result
>>>from fib import fib
>>>fib(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
This statement does not import the entire module fib into the current
namespace; it just introduces the item fibonacci from the module fib into the
global symbol table of the importing module.
• The from...import * Statement provides an easy way to import all the
items from a module into the current namespace; however, this
statement should be used sparingly.
• It is also possible to import all names from a module into the current
namespace by using the following import statement.
• The from...import * Statement has the following syntax- from
modname import *
>>>from fib import *
>>>fib1(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>>fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>>
Here the statement from fib import * imports all functions defined inside the
module fib.py
dir() Function
• Used to find the names a module defines and returns a sorted list of
strings
– >>> import mod
195
Self-Instructional Material
Files >>>dir(mod)
[‘_name_’, ‘m1’, ‘m2’]
• Without arguments, it lists the names currently defined (variables,
modules, functions, etc)
• Does not list names of built-in functions and variables
NOTES Use _bulltin_to view all built-in functions and varia
environment. Options are given to the interpre ter on the command line
as follows:
python [options] [-c cmd | filename | - ] [args]
Here’s a list of the most common command-line options:
196
Self-Instructional Material
Files
1 -d NOTES
It provides debug output.
2 -O
It generates optimized bytecode (resulting in .pyo files).
3 -S
Do not run import site to look for Python paths on startup.
4 -v
verbose output (detailed trace on import statements).
5 -X
disable class-based built-in exceptions (just use strings); obsolete
starting with version 1.6.
6 -c cmd
run Python script sent in as cmd string
7 file
run Python script from given file
197
Self-Instructional Material
Files eliminating errors is called debugging. Errors can be classified into
three major groups:
Syntax errors.
Runtime errors.
Logical errors.
NOTES
4. Python also allows you to create your own exceptions by deriving
classes from the standard built-in exceptions. We can add user-
defined exceptions by creating a new class in Python. The trick here
is to derive the custom exception class from the base exception class.
Most of the built-in exceptions use the same technique to enforce
their exceptions
5. A function is used within a program through function call. It invokes
the function. When function is invoked, then program control jumps
to the called function to execute the statements that are part of that
function. Once the function is executed, the program control is return
back to calling function.
11.16 SUMMARY
Text files are structured as a sequence of lines, where each line
includes a sequence of characters.
File is a named location on disk to store related information. It is used
to permanently store data in a non-volatile memory (e.g. hard disk).
Errors can be classified into three major groups: Syntax errors,
Runtime errors and Logical errors
The error message has two parts: type of error before the colon, and
speci_cs about the error after the colon
Python using a key word try to organize a block of code that is
expected to produce an error and throw an exception.
11.17 KEYWORDS
Seek (): It sets the file's current position at the offset. The whence argument
is optional and defaults to 0, which means absolute file positioning, other
values are 1 which means seek relative to the current position and 2 means
seek relative to the file's end.
Errors: Errors or mistakes in a program are often referred to as bugs. They
are almost always the fault of the programmer.
ValueError: It is raised when the built-in function for a data type has the
valid type of arguments, but the arguments have invalid values specified.
Exception: An exception is an error that happens during execution of a
program. When that error occurs, Python generate an exception that can be
handled, which avoids the program to crash.
198
Self-Instructional Material
Files
11.18 SELF ASSESSMENT QUESTIONS AND EXERCISES
199
Self-Instructional Material
Perl
BLOCK – V
OPEN SOURCE PROGRAMMING
NOTES LANGUAGE-PERL
UNIT- 12 PERL
Structure
12.0 Introduction
12.1 Objective
12.2 Perl Backgrounder
12.3 Perl Overview
12.4 Parsing rules
12.5 Variables
12.5.1 Creating Variables
12.5.2 Scalar Variables
12.5.3 Array Variables
12.5.4 Hash Variables
12.5.5 Variable Context
12.6 Datatypes
12.7 Answers to Check Your Progress
12.8 Summary
12.9 Keywords
12.10 Self Assessment Questions and Exercises
12.11 Further Readings
12.0 INTRODUCTION
Open source programming languages are freely available to the user one such
software is Perl Programming language which consists of many packages for
the web development creating a platform for all users to work with it.
12.1 OBJECTIVE
This unit helps the user to learn and understand the Perl
Parsing Rules
Variables and Datatypes
200
Self-Instructional Material
12.2 PERL BACKGROUNDER Perl
Perl is a general-purpose programming language originally developed for text
manipulation and now used for a wide range of tasks including system
administration, web development, network programming, GUI development,
and more. Perl is a stable, cross platform programming language. Though NOTES
Perl is not officially an acronym but few people used it as Practical
Extraction and Report Language. It is used for mission critical projects in the
public and private sectors. Perl is Open Source software, licensed under its
Artistic License, or the GNU General Public License (GPL).Perl was created
by Larry Wall. Perl 1.0 was released to usenet's alt.comp.s ources in 1987.At
the time of writing this tutorial, the latest version of Perl was 5.16.2.Perl is
listed in the Oxford English Dictionary. PC Magazine announced Perl as the
finalist for its 1998 Technical Excellence Award in the Development Tool
category.
Self-Instructional Material
Perl converted ( as the program runs) into machine instructions. So it is not quite
the same as shells, or Tcl, which are strictly interpreted without an
intermediate representation. It is also not like most versions of C or C++,
which are compiled directly into a machine dependent format. It is
somewhere in between, along with Python and awk and Emacs .elc files.
NOTES
12.4 PARSING RULES
The Swedish Chef lex grammar, by John Hagerman, is a great example of a
simple text filter. It's also a lot of fun, having amused many computer science
and engineering students on the eve of their finals. I will show an example of
porting the chef’s grammar to Perl using the Parse::RecDescent module (not
the ideal choice for this task -- the Parse::Lex module would be a better one).
This section is intended only as an introduction to the rules of building a
Parse::RecDescent syntax and will include actions, remembering the state,
rejecting productions, and lexing text. Remember to try the chef.pl script
yourself -- you may just find yourself addicted.
The chef.pl script is an almost exact copy of the chef.l lex grammar. The
$niw variable is set to 0 at startup, because many rules test it to see if they
should be accepted or rejected. $niw stands for "not in word", and it is set to
1 when the parser is inside a word. The directive to Parse::RecDescent will
reject a rule if the variable named in the directive is non-zero. So keep in
mind that $niw = 0 means that you are not inside a word.
The skip variable was set to '' (empty string), so all input, including spaces,
goes to the token directive. Also, the chef rule ends on \z, which is the end of
the string. Usually, \Z is used, but that can also match a newline in Perl, and
those may also be in the input.
The chef rule: The grammar begins with the chef rule. The chef rule matches
a number of tokens, up to the \z end of string. Those two elements of the chef
rule are called "productions." Any rule must be made up of productions. An
action can be part of a production; it is marked by braces {} and contains Perl
code. It doesn't match anything -- it is simply executed.
The token rule: The token rule can match any of a number or sequences,
somewhat arbitrarily, which I named to match the chef.l grammar. I'll explain
a few examples, so that the grammar correspondence is clear.
The basic grammar definitions of a word/non-word character:
chef.pl: WC: /[A-Za-z']/
chef.pl: NW: /[^A-Za-z']/
chef.l: WC [A-Za-z']
chef.l: NW [^A-Za-z']
The an rule: The simplest rules do not depend on anything. The an rule is a
good example: Whenever it sees 'an', it prints 'un'. Also, it sets $niw to 1
(remember, that means you are inside a word).
202
Self-Instructional Material
chef.pl: an: /an/ { $niw = 1; print 'un' }
Perl
chef.l: "an" { BEGIN INW; printf("un"); }
The ax rule: The next more complex rule is the ax rule. It says, if an 'a'
shows up, and is followed by a word character WC, print 'e'. The ...WC NOTES
production syntax means that a word character must follow the a, but will not
be consumed in the match. Thus, 'aan' produces 'eun' with an and ax rules.
The rule sets $niw to 1 (inside a word).
chef.pl: ax: /a/ ...WC { $niw = 1; print "e" }
chef.l: "a"/{WC} { BEGIN INW; printf("e"); }
The en rule: The en rule works exactly like the ax rule, but with a NW (non-
word) production anticipated to follow. This means that the 'en' must be at the
end of a word.
chef.pl: en: /en/ ...NW { $niw = 1; print "ee" }
chef.l: "en"/{NW} { BEGIN INW; printf("ee"); }
The ew rule: The ew rule succeeds only if you are inside a word. That's why
you reject it if $niw is 0.
chef.pl: ew: /ew/ { $niw = 1; print "oo" }
chef.l: "ew" { BEGIN INW; printf("oo"); }
The i rule: The i rule will succeeds only if you are inside a word, and have
not seen another i yet. It augments $i_seen to 1, and $i_seen is only set back
to 0 if a non-word character or a newline are seen.
chef.pl: i: /i/ { $niw=1;$i_seen=1; print "ee" }
chef.l: "i" { BEGIN INW; printf(i_seen++ ? "i" : "ee"); }
The end of sentence rule: The end of sentence markers [.!?] in any quantity,
followed by space, will be printed, followed by the famous (or infamous, take
your pick) "Bork Bork Bork!" message. The actual behavior deviates slightly
from the original chef filter, only because I like it better that way (one can
never have enough Bork messages). The $item[1] syntax means that the
spaces won't be matched, since they are known as $item[2] to
Parse::RecDescent.
chef.pl: end_of_sentence: /[.?!]+/ /\s+/
{ $niw = 0; $i_seen = 0;
print $item[1] . "\nBork Bork Bork!\n" }
chef.l: [.!?]$
{ BEGIN NIW;
i_seen = 0;
203
Self-Instructional Material
Perl printf("%c\nBork Bork Bork!",
yytext[0]);
}
NOTES The extend-grammar process rule: The process rule can consist of a query
or a definition. Unless it finds one or the other, it triggers a message in the
main loop. The extend-grammar query rules: The query rule consists of a do
you know production, followed by a name or a proper name. For a name, the
action is to print a message that it is unknown. For a proper name (as defined
by the proper name rule), the action is to print out a message that it is known.
Two rules of the same name are equivalent to one rule with two alternative
productions, the extend-grammar definition rule: The heart of this extensible
grammar is the definition rule. If a name is followed by 'exists', then the
action will extend the parser with a new rule for proper name. You can
modify the very grammar you are executing, while it's running.
12.5 VARIABLES
Variables are the reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory. Based on the
data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data
types to variables, you can store integers, decimals, or strings in these
variables. We have learnt that Perl has the following three basic data types −
Scalars
Arrays
Hashes
Self-Instructional Material
$salary = 1445.50; # A floating point
Perl
Here 25, "John Paul" and 1445.50 are the values assigned to $age, $name and
$salary variables, respectively. Shortly we will see how we can assign values
to arrays and hashes.
NOTES
205
Self-Instructional Material
Perl print "\$names[2] = $names[2]\n";
Here we used escape sign (\) before the $ sign just to print it. Other Perl will
understand it as a variable and will print its value. When executed, this will
produce the following result −
NOTES
$ages[0] = 25
$ages[1] = 30
$ages[2] = 40
$names[0] = John Paul
$names[1] = Lisa
$names[2] = Kumar
Self-Instructional Material
This will produce the following result −
Perl
Given names are : John Paul Lisa Kumar
Number of names are : 3
Here @names is an array, which has been used in two different contexts. First NOTES
we copied it into any other array, i.e., list, so it returned all the elements
assuming that context is list context.
12.6 DATATYPES
Perl is a loosely typed language and there is no need to specify a type for
your data while using in your program. The Perl interpreter will choose the
type based on the context of the data itself.
Perl has three basic data types: scalars, arrays of scalars, and hashes of
scalars, also known as associative arrays. Here is a little detail about these
data types.
Scalars are simple variables. They are preceded by a dollar sign ($). A
scalar is either a number, a string, or a reference. A reference is actually an
address of a variable, which we will see in the upcoming chapters.
Arrays are ordered lists of scalars that you access with a numeric index,
which starts with 0. They are preceded by an "at" sign (@).
Hashes-Hashes are unordered sets of key/value pairs that you access using
the keys as subscripts. They are preceded by a percent sign (%).
Numeric Literals-Perl stores all the numbers internally as either signed
integers or double-precision floating-point values. Numeric literals are
specified in any of the following floating-point or integer formats
String Literals-Strings are sequences of characters. They are usually
alphanumeric values delimited by either single (') or double (") quotes. They
work much like UNIX shell quotes where you can use single quoted strings
and double quoted strings.
Double-quoted string literals allow variable interpolation, and single-quoted
strings are not. There are certain characters when they are proceeded by a
back slash, have special meaning and they are used to represent like newline
(\n) or tab (\t).You can embed newlines or any of the following Escape
sequences directly in your double quoted strings
Escape Meaning
sequence
\\ Backslash
\' Single quote
\" Double quote
\a Alert or bell
\b Backspace
\f Form feed
207
Self-Instructional Material
Perl \n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\0nn Creates Octal formatted numbers
NOTES
\xnn Creates Hexideciamal formatted numbers
\cX Controls characters, x may be any character
\u Forces next character to uppercase
\l Forces next character to lowercase
Example
Let's see again how strings behave with single quotation and double
quotation. Here we will use string escapes mentioned in the above table and
will make use of the scalar variable to assign string values.
Live Demo
#!/usr/bin/perl
# This is case of interpolation.
$str = "Welcome to \ntutorialspoint.com!";
print "$str\n";
# This is case of non-interpolation.
$str = 'Welcome to \ntutorialspoint.com!';
print "$str\n";
Self-Instructional Material
print "$str\n";
Perl
# A portion of line will become capital.
$str = "Welcome to \Ututorialspoint\E.com!";
NOTES
print "$str\n";
# Backsalash non alpha-numeric including spaces.
$str = "\QWelcome to tutorialspoint's family";
print "$str\n";
This will produce the following result −
Welcome to
tutorialspoint.com!
Welcome to \ntutorialspoint.com!
Welcome to tutorialspoint.com!
WELCOME TO TUTORIALSPOINT.COM!
Welcome to TUTORIALSPOINT.com!
Welcome\ to\ tutorialspoint\'s\ famil
Self-Instructional Material
Perl 4. Perl has the following three basic data types:
Scalars
Arrays
Hashes
NOTES 5. A scalar is a single unit of data. That data might be an integer number,
floating point, a character, a string, a paragraph, or an entire web
page. Simply saying it could be anything, but only a single thing.
12.8 SUMMARY
Perl has three basic data types: scalars, arrays of scalars, and hashes
of scalars, also known as associative arrays.
An array is a variable that stores an ordered list of scalar values.
A scalar is a single unit of data. That data might be an integer
number, floating point, a character, a string, a paragraph, or an entire
web page.
Perl variables do not have to be explicitly declared to reserve
memory space.
12.9 KEYWORDS
The extend-grammar process rule: The process rule can consist of a query
or a definition.
Hashes-Hashes are unordered sets of key/value pairs that you access using
the keys as subscripts. They are preceded by a percent sign (%).
Numeric Literals-Perl stores all the numbers internally as either signed
integers or double-precision floating-point values. Numeric literals are
specified in any of the following floating-point or integer formats
Until loop: Repeats a statement or group of statements until a given condition
becomes true. It tests the condition before executing the loop body.
210
Self-Instructional Material
Perl
12.11. FURTHER READINGS
Rémy Card, Eric Dumas, and Franck Mével. The Linux kernel book.
John Wiley & Sons, Inc., 2003. NOTES
211
Self-Instructional Material
Control Structures
UNIT- 13 CONTROL STRUCTURES
Structure
NOTES 13.0 Introduction
13.1 Objective
13.2 Control Structures
13.2.1 Decision Making Statements in Perl
13.3 Subroutines
13.3.1 Define and Call a Subroutine
13.3.2 Passing Arguments to a Subroutine
13.3.3 Passing Lists to Subroutines
13.3.4 Passing Hashes to Subroutines
13.3.5 Returning Value from a Subroutine
13.4 Answers to Check Your Progress
13.5 Summary
13.6 Keywords
13.7 Self Assessment Questions and Exercises
13.8 Further Readings
13.0 INTRODUCTION
The control structures are important statements in programming languages.
This unit explains the basic control structures and subroutines of Perl
Programming Languages. The different control statements and their syntax
are discussed
13.1 OBJECTIVE
This unit helps the user to start their Perl programming by understanding
Control Structures
Subroutines
212
Self-Instructional Material
13.2.1 Decision making statements in Perl Control Structures
The number 0, the strings '0' and "" , the empty list () , and undef are all false
in a boolean context and all other values are true. Negation of a true value by!
Or not returns a special false value. Perl programming language provides the
following types of conditional statements. NOTES
7. switch statement-With the latest versions of Perl, you can make use of the
switch statement. which allows a simple way of
comparing a variable value against various conditions.
8. The ? : Operator-Let's check the conditional operator ? :which can be
used to replace if...else statements. It has the following general form
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement
of the colon.
The value of a ? Expression is determined like this: Exp1 is evaluated. If it is
true, then Exp2 is evaluated and becomes the value of the entire ? expression.
If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the
expression. Below is a simple example making use of this operator?
213
Self-Instructional Material
Control Structures
NOTES
foreach loop-The foreach loop iterates over a normal list value and sets the
variable VAR to be each element of the list in turn.
do...while loop-Like a while statement, except that it tests the condition at the
end of the loop body.
214
Self-Instructional Material
nested loops-You can use one or more loop inside any another while, for or
Control Structures
do..while loop.
next statement-Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
goto statement-Perl supports a goto command with three forms: goto label,
goto expr, and goto &name.
#!/usr/local/bin/perl
for( ; ; ) {
printf "This loop will run forever.\n";
}
When the conditional expression is absent, it is assumed to be true. You may
have an initialization and increment expression, but as a programmer more
commonly use the for (;;) construct to signify an infinite loop.
215
Self-Instructional Material
Control Structures
NOTES
13.3 SUBROUTINES
A Perl subroutine or function is a group of statements that together performs
a task. You can divide up your code into separate subroutines. How you
divide up your code among different subroutines is up to you, but logically
the division usually is so each function performs a specific task.
Perl uses the terms subroutine, method and function interchangeably.
216
Self-Instructional Material
Let's have a look into the following example, which defines a simple function
Control Structures
and then call it. Because Perl compiles your program before executing it, it
doesn't matter where you declare your subroutine.
Live Demo
NOTES
#!/usr/bin/perl
# Function definition
sub Hello {
print "Hello, World!\n";
}
# Function call
Hello();
When above program is executed, it produces the following result −
Hello, World!
217
Self-Instructional Material
Control Structures print "Average for the given numbers : $average\n";
}
# Function call
NOTES
Average(10, 20, 30);
When above program is executed, it produces the following result
Average for the given numbers : 20
Self-Instructional Material
my $value = $hash{$key};
Control Structures
print "$key : $value\n";
}
} NOTES
219
Self-Instructional Material
Control Structures
Check your Progress
1. What are Subroutines?
2. Define Passing Arguments to a Subroutine?
3. Define Passing Hashes to Subroutines?
NOTES 4. Define Returning Value from a Subroutine?
5. What is Control Structures?
13.5 SUMMARY
Perl conditional statements helps in the decision making, which
require that the programmer specifies one or more conditions to be
evaluated
A loop statement allows us to execute a statement or group of
statements multiple times and following is the general form of a loop
statement in most of the programming languages programming
language provides the following types of loop to handle the looping
requirements.
Loop becomes infinite loop if a condition never becomes false. The
for loop is traditionally used for this purpose.
220
Self-Instructional Material
Control Structures
13.6 KEYWORDS
if statement: An if statement consists of a boolean expression followed by NOTES
one or more statements.
While loop: Repeats a statement or group of statements while a given
condition is true. It tests the condition before executing the loop body.
Until loop: Repeats a statement or group of statements until a given condition
becomes true. It tests the condition before executing the loop body.
221
Self-Instructional Material
Packages And Modules
UNIT 14
NOTES
PACKAGES AND MODULES
Structure
14.0 Introduction
14.1. Objective
14.2 Packages
14.3 Modules
14.3.1Create the Perl Module Tree
14.3.2 Installing Perl Module
14.4 Working with Files
14.4.1 Opening and Closing Files
14.4.2 Close Function
14.5 Data Manipulation
14.6 Answers to Check Your Progress
14.7 Summary
14.8 Keywords
14.9 Self Assessment Questions and Exercises
14.10 Further Readings
14.0. INTRODUCTION
This unit describes the Perl programming language packages and modules
regarding the working of files and data manipulation techniques. The
working with files and how to establish the modules with data manipulation
in Perl is explained.
14.1 OBJECTIVE
The users understands and learns the Perl Programming Concepts such as
Working with Files
Data Manipulation
14.2 PACKAGES
The package statement switches the current naming context to a specified
namespace (symbol table). Thus A package is a collection of code which
lives in its own namespace.A namespace is a named collection of unique
variable names (also called a symbol table).Namespaces prevent variable
name collisions between packages.
Packages enable the construction of modules which, when used, won't
clobber variables and functions outside of the modules's own namespace. The
222
Self-Instructional Material
package stays in effect until either another package statement is invoked, or
Packages And Modules
until the end of the current block or file. You can explicitly refer to variables
within a package using the :: package qualifier. Following is an example
having main and Foo packages in a file. Here special variable PACKAGE has NOTES
been used to print the package name.
Live Demo
#!/usr/bin/perl
# This is main package
$i = 1;
print "Package name : " , __PACKAGE__ , " $i\n";
package Foo;
# This is Foo package
$i = 10;
print "Package name : " , __PACKAGE__ , " $i\n";
package main;
# This is again main package
$i = 100;
print "Package name : " , __PACKAGE__ , " $i\n";
print "Package name : " , __PACKAGE__ , " $Foo::i\n";
Self-Instructional Material
Packages And Modules Following example shows its usage
Live Demo
NOTES #!/usr/bin/perl
package Foo;
print "Begin and Block Demo\n";
BEGIN {
print "This is BEGIN Block\n"
}
END {
print "This is END Block\n"
}
1;
When above code is executed, it produces the following result
This is BEGIN Block
Begin and Block Demo
This is END Block
14.3 MODULES
A Perl module is a reusable package defined in a library file whose name is
the same as the name of the package with a .pm as extension.A Perl module
file called Foo.pm might contain statements like this.
#!/usr/bin/perl
package Foo;
sub bar {
print "Hello $_[0]\n"
}
sub blat {
print "World $_[0]\n"
}
1;
224
Self-Instructional Material
Foo::bar( "a" );
Packages And Modules
Foo::blat( "b" );
You must have noticed that the subroutine names must be fully qualified to NOTES
call them. It would be nice to enable the subroutine bar and blat to be
imported into our own namespace so we wouldn't have to use the Foo::
qualifier.
#!/usr/bin/perl
use Foo;
bar( "a" );
blat( "b" );
Notice that we didn't have to fully qualify the package's function names. The
use function will export a list of symbols from a module given a few added
statements inside a module.require Exporter;
@ISA = qw(Exporter);
Then, provide a list of symbols (scalars, lists, hashes, subroutines, etc) by
filling the list variable named @EXPORT: For Example −
package Module;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(bar blat);
sub bar { print "Hello $_[0]\n" }
sub blat { print "World $_[0]\n" }
sub splat { print "Not $_[0]\n" } # Not exported!
1;
225
Self-Instructional Material
Packages And Modules $h2xs -AX -n Person
This will produce the following result
NOTES Writing Person/lib/Person.pm
Writing Person/Makefile.PL
Writing Person/README
Writing Person/t/Person.t
Writing Person/Changes
Writing Person/MANIFEST
Here is the descritpion of these options −
-A omits the Autoloader code (best used by modules that define a large
number of infrequently used subroutines).
-X omits XS elements (eXternal Subroutine, where eXternal means external
to Perl, i.e., C).
-n specifies the name of the module.
So above command creates the following structure inside Person directory.
Actual result is shown above.
226
Self-Instructional Material
capable of read/write access, so you can read from and update any file or
Packages And Modules
device associated with a file handle. However, when you associate a file
handle, you can specify the mode in which the file handle is opened.
NOTES
Three basic file handles are - STDIN, STDOUT, and STDERR, which
represent standard input, standard output and standard error devices
respectively.
Open Function
Following is the syntax to open file.txt in read-only mode. Here less than <
sign indicates that file has to be opend in read-only mode.
open(DATA, "<file.txt");
Here DATA is the file handle, which will be used to read the file. Here is the
example, which will open a file and will print its content over the screen.
#!/usr/bin/perl
open(DATA, "<file.txt") or die "Couldn't open file file.txt, $!";
while(<DATA>) {
print "$_";
}
Following is the syntax to open file.txt in writing mode. Here less than > sign
indicates that file has to be opend in the writing mode.
open(DATA, ">file.txt") or die "Couldn't open file file.txt, $!";
This example actually truncates (empties) the file before opening it for
writing, which may not be the desired effect. If you want to open a file for
reading and writing, you can put a plus sign before the > or < characters.
For example, to open a file for updating without truncating it −
open(DATA, "+<file.txt"); or die "Couldn't open file file.txt, $!";
227
Self-Instructional Material
Packages And Modules open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!";
A double >> opens the file for appending, placing the file pointer at the end,
so that you can immediately start appending information. However, you can't
NOTES
read from it unless you also place a plus sign in front of it −
open(DATA,"+>>file.txt") || die "Couldn't open file file.txt, $!";
Following is the table, which gives the possible values of different modes
< or r-Read Only Access
> or w-Creates, Writes, and Truncates
>> or a-Writes, Appends, and Creates
+< or r+-Reads and Writes
+> or w+-Reads, Writes, Creates, and Truncates
+>> or a+-Reads, Writes, Appends, and Creates
Sysopen Function
The sysopen function is similar to the main open function, except that it uses
the system open() function, using the parameters supplied to it as the
parameters for the system function For example, to open a file for updating,
emulating the +<filename format from open
sysopen(DATA, "file.txt", O_RDWR);
Or to truncate the file before updating
sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );
You can use O_CREAT to create a new file and O_WRONLY- to open file
in write only mode and O_RDONLY - to open file in read only mode.The
PERMS argument specifies the file permissions for the file specified, if it has
to be created. By default it takes 0x666.
Following is the table, which gives the possible values of MODE.
O_RDWR-Read and Write
O_RDONLY-Read Only
O_WRONLY-Write Only
O_CREAT-Create the file
O_APPEND-Append the file
O_TRUNC-Truncate the file
O_EXCL-Stops if file already exists
228
Self-Instructional Material
O_NONBLOCK-Non-Blocking usability
Packages And Modules
Self-Instructional Material
Packages And Modules getc
Read Function
NOTES The read function reads a block of information from the buffered filehandle:
This function is used to read binary data from the file.
read FILEHANDLE, SCALAR, LENGTH, OFFSET
read FILEHANDLE, SCALAR, LENGTH
The length of the data read is defined by LENGTH, and the data is placed at
the start of SCALAR if no OFFSET is specified. Otherwise data is placed
after OFFSET bytes in SCALAR. The function returns the number of bytes
read on success, zero at end of file, or undef if there was an error.
230
Self-Instructional Material
double quotes—for two reasons. First, I want to be able to use double quotes
Packages And Modules
inside my programs for literals, and double quotes don't nest in the shell.
Second, I have to prevent shell interpolation, and single quotes make it easy.
For example, if I use double quotes, then NOTES
231
Self-Instructional Material
Packages And Modules closes the filehandle as appropriate. With the diamond operator, it's as simple
as:
while ( my $line = <> ) {
NOTES
# do something
}
Perl keeps the name of the currently open file in $ARGV. The $. line counter
does not reset at the beginning of each file.The diamond operator figures
prominently in much Perl command-line magic, so it behooves you to get
comfortable with it.
-n and -p: Automatic Looping Powerhouses
The -n and -p options are the real workhorse options. They derive from the
Awk metaphor of "Do something to every line in the file," and work closely
with the diamond operator.The following program prepends each line with its
line number:
while (<>) {
$_ = sprintf( "%05d: %s", $., $_ );
print; # implicitly print $_
}
The construct of "Walk through a file, and print $_ after you do some magic
to it" is so common that Perl gives us the -p option to implement it for us.
The previous example can be written as:
#!/usr/bin/perl -p
$_ = sprintf( "%05d: %s", $., $_ );
or even shorter as:
$ perl -p -e'$_ = sprintf( "%05d: %s", $. $_ )'
The -n option is just like -p, except that there's no print at the bottom of the
implicit loop. This is useful for grep-like programs when you're only
interested in selected information. You might use it to print only commented-
out lines from your input, defined as beginning with optional whitespace and
a pound sign:
$ perl -n -e'print if /^\s*#/'
The next program prints every numeric value that looks like it's part of a
dollar value, as in "$43.50."
#!/usr/bin/perl -n
while ( /\$(\d+\.\d\d)/g ) {
232
Self-Instructional Material
print $1, "\n";
Packages And Modules
}
NOTES
Check your Progress
1. What is symbol table?
2. What is the Require function in module?
3. What is the Use function in module?
4. What is Perl Module Tree?
5. What is Read Function?
4. When you are ready to ship your Perl module, then there is standard
way of creating a Perl Module Tree. This is done using h2xs utility.
This utility comes along with Perl. Here is the syntax to use h2xs
$h2xs -AX -n ModuleName.
233
Self-Instructional Material
Packages And Modules
14.7 SUMMARY
Packages enable the construction of modules which, when used,
NOTES won't clobber variables and functions outside of the modules's own
namespace.
A Perl module is a reusable package defined in a library file whose
name is the same as the name of the package with a .pm as extension.
A file handle is a named internal Perl structure that associates a
physical file with a name.
Perl's diamond operator, <>, has a great deal of magic built into it,
making operations on multiple files easy.
Three basic file handles are - STDIN, STDOUT, and STDERR,
which represent standard input, standard output and standard error
devices respectively.
14.8 KEYWORDS
234
Self-Instructional Material
Packages And Modules
Rasmus Lerdorf and Levin Tatroe. Programming PHP. " O'Reilly
Media, Inc., 2002.
NOTES
Wesley J. Chun. Core Python Programming. Prentice Hall, 2001.
235
Self-Instructional Material
Model Question Paper
12. What are shells? Describe the different types of shells available in
Linux.
(OR)
Explain: Setting up email servers. (i) Using postfix (SMTP services)
(ii) Courire (IMAP& POP3).
13. What are the main objectives of file sharing? Explain the methods
used in Linux for performing file sharing services.
(OR)
Explain the usage of source code versioning and management tools
using CVS to manage source code revisions, patch and duff.
14. Explain the Model Driven Architecture.
(OR)
236
Self-Instructional Material
Explain the Features of Meta Object facility.
Model Question Paper
15. Discuss the basics of the X Windows server architecture.
(OR) NOTES
237
Self-Instructional Material