## Pandas Numpy and Matplotlib

I have created demo code with Jupyter Notebook, which can be viewed here: https://github.com/marcuspaget/pythonDSFromScratch/blob/master/PandasDemo.md

Panda – Python Data Analysis Library

Quick install with:

`pip install pandas`

Python’s answer to R’s DataFrames for data manipulation

Providing tools to read and write data between data structures and different formats: CSV and text files, Microsoft Excel, SQL databases, and the fast HDF5 format;

Easily to manipulate, slice and dice data, with integrated indexing.

Possible to convert HDF5 to HDFS for ingestion in Hadoop

Time series-functionality:

• Date range generation & modification
• Frequency conversion
• Moving window statistics
• Join time series without losing data

Numpy – Python Number Library

`pip install numpy`
`Create, manipulate , slice and run ops i.e std, mean, min, max, etc`
`Please see link at top for examples`

Matplotlib – Python plotting and figures

`pip install matplotlib`
`Graph data from lists, dataframes, etc.For example:`

I have created demo code with Jupyter Notebook, which can be viewed here: https://github.com/marcuspaget/pythonDSFromScratch/blob/master/PandasDemo.md

## Using tapply to sum by category

Good use of R’s tapply function to summary data ..

## read a csv file into a table called x – the first row contains column names

`x<-read.table("2014-tax.csv",sep=",",header=T)`

## In my instance column names are Item,Amount,Cat,Month,Who
## split out by Who

`bob<-x[x\$Who == "bob",] jane<-x[x\$Who == "jane",]`

## Spin around each row (obs) and sum the Amount

`print(tapplybob\$Amount,bob\$Cat,sum))`

## Typical output for bob #

```#  books  equipment licences stationery  supplies    telephone
#  303.00  694.27     132.00   345.50      96.00       30.00 #
```

# Then for jane

`print(tapply(jane\$Amount,jane\$Cat,sum)) `

```# books equipment licences stationery supplies telephone
# 163.0  583.0      348.0     678.4    11543.0    NA
# #
```

## Arduino Hacking

Whilst on 5 week long service leave – created my first Arduino Hack to control an LCD (Liquid Crystal Display) I had lying around for last 6 years đź™‚

Please see video below and all code is here:

https://github.com/marcuspaget/ArduinoLCD

Here is the video that shows all the steps, please feel free to leave comments below or on youtube if keen to discuss.

## Python Dict

Sample code for working with Python Dicts

# init users list of dicts, print out id 1, then init friends list of tuples

users = [

`     { "id": 0, "name": "Bob" },     { "id": 1, "name": "Dunn" },     { "id": 2, "name": "Sue" },     { "id": 3, "name": "Chi" },     { "id": 4, "name": "Thor" },     { "id": 5, "name": "Clive" },     { "id": 6, "name": "Hicks" },     { "id": 7, "name": "Devin" },     { "id": 8, "name": "Kate" },     { "id": 9, "name": "Klein" },     { "id": 10, "name": "Jen" } `

]

`i=0for user in users:     if(users[i]["name"]=="Bob"):         print("Bob ID: ",users[i]["id"])     i+=1friends= [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]`

# spin through all users and create empty list to store list, then populate

`for user in users:     user["friends"]=[]`

# populate empty list with all left side of tuple with right and vice versa

`for i,j in friends:     users[i]["friends"].append(users[j])     users[j]["friends"].append(users[i])`

# function to return length based on passed in user

`def number_of_friends(user):         """how many friends does _user_ have?"""    return len(user["friends"]) # length of friend_ids list`

# total up all friends

`total_connection = sum(number_of_friends(user)                              for user in users) # 24 `

# grab number of users

`num_users = len(users)avg_connections = total_connection / num_users # 2.4 `

# create a list (user_id, number_of_friends)

`num_friends_by_id = [(user["id"], number_of_friends(user)) for user in users] print(sorted(num_friends_by_id,key=lambda pair: pair[1],                      reverse=True))`

# Output – largest to smallest

`[(1, 3), (2, 3), (3, 3), (5, 3), (8, 3), (0, 2), (4, 2), (6, 2), (7, 2), (9, 1), (10, 0)]`

## Powershell Intro

In recent years it has become necessary to learn Powershell. This is for a number of reasons, but predominately because certain automations are only possible via it. More on that later.

First – how to run powershell … simply windows key + R and powershell.

Or Windows key and start typing powershell – select Windows PowerShell ISE. This provides an IDE.

Variables

\$single_quoted_string = 'a '
\$double_quoted_string = "a string – \$x"
Write-Host \$single_quote_string
Write-Host \$double_quoted_string

# can enforce with [string]

## Integers
[int]\$int_one = 1
\$int_two = 2
\$int_one + \$int_two

## Arrays
[array]\$arr = @(1,'str_var',5)
\$array

## Hash tables
[hashtable]\$htab = @{'key1' = 'value1'; 'key2' = 'value2'}
\$htab

\$htab.Get_Item('key1')
\$htab.key1

\$htab.Set_Item(“key1”, “mod_val1”)
\$htab.Remove('key1')

If/Then

\$a = 1
if (\$a -eq 1) {
Write-Host 'a equals 1'
} else {
Write-Host 'a is not equal to 1'
}

# also possible to elseif

} elseif (\$a -eq 3) {

Switch

ď»ż\$a = 1

switch (\$a) {
1 {“Value 1”}
2 {“Value 2”}
3 {“Value 3”}
default {“Value exceeds threshold.”}
}

\$b = “X365”

switch -wildcard (\$b) {
“Z*” {“Val Z”}
“Y*” {“Val Y”}
“X*” {“Val X”}
default {“Val outside parameters.”}
}

## 1 – Lessons begin

Welcome to Coding-School.com old school!

Some of the tips, techniques and code freely imparted here, I’ve searched the web previously and come back empty handed. Then set about hand crafting my own solutions – which you get completely for free! đź™‚

What gives me the audacity, to think I could possible teach anyone anything Technical! Well here is my 5 line bio:

• Over 25 years IT work experience. Working with IBM, Compaq, ICL, Dunn and Bradstreet and 2 Banks.
• Dabbling with Python for 8 years.
• Dabbling with NodeJS for 10 years.
• Dabbling with LDAP (directory services) for around 15 years.
• Dabbling with PHP for around 20 years.
• Dabbling with Perl for the last 25 years.
• Over 25 years UNIX Admin. Well you might ask, what the hell has that do to with Coding. IMHO – best Admins code all the time!! đź™‚

Cheers and enjoy,

Mark

## Perl Intro

### Introduction to Perl

Perl is an acronym, short for Practical Extraction and Report Language. It was designed by Larry Wall as a tool for writing programs in the UNIX environment (Perl is a stable, cross platform programming language). Perl has the power and flexibility of a high-level programming language such as C. In fact many of the features of the language are borrowed from C. Like shell script languages, Perl does not require a compiler – the Perl interpreter runs your programs. This means that Perl is ideal for producing quick solutions to small programming problems and creating prototypes to test potential solutions to larger problems.

• Perl is a stable, cross platform programming language.
• It is used for mission critical projects in the public and private sectors.
• Perl is Open Source software, licensed under the GNU General Public License (GPL).
• Perl was created by Larry Wall.
• Perl is listed in the Oxford English Dictionary

mod_perl allows the Apache web server to embed a Perl interpreter.

Perl’s DBI package makes web-database integration easy.

@INC is also printed as part of the output of
% perl -V

Example on how to read a url/web page in perl

```#!/usr/bin/perl
use LWP::Simple;
my \$url="http://www.gnulamp.com/perl.html";
my \$webdata=get \$url;
print \$webdata;
```

## Shiny DashBoard

“Having studied Data Science since April 2014, felt it a good time to get to know Rstudioâ€™s Shiny Server! So sourced data.gov.auâ€™s Disaster Events and built an interactive dashboard. Writing up my experiences as a way of introduction, in the hope it might help others to learn Shiny Server.”

If you just want to see the demo first Â» CLICK HERE Â«

1. First requirement is to have a fair understanding of R. There are a ton of courses online, such as on Rstudio, EDX and Coursera. My favourite course is MIT’s Analytics Edge. As a currently archived course you can complete it self paced, although assessments are disabled.
2. Next to complete the Shiny Tutorial. It is very comprehensive and the only requirement is Rstudio, naturally. Previously the tutorial comprised 3 parts, but now are presented in the single video lasting a bit of 2 hours 25 minutes. I highly recommend it.
3. Study the Shiny Dashboard Instructions – my source code might help too
4. References:
Now onto my demo!

The Australian government provides public access to numerous data sets and encourages re-use. Therefore chose data from data.gov.au to build my demo, as it is freely available.

This is what the data looked like:

 Quick preview of what I achieved thanks to Shiny Dashboards:
The example I created converts a CSV file to data tables, graphs and map of Australia using uses RStudio’s Shiny Dashboard =>

Australia Government Disaster Events Dashboard

And the Source code

Lastly this tutorial helped with the maps.

Enjoy and feel free to comment below – would be good to receive feedback.

## Perl Signals

### Perl Signals

Perl allows you to trap signals using the %SIG associative array. Using the signals you want to trap as the key, you can assign a subroutine to that signal. The %SIG array will only contain those values which the programmer defines. Therefore, you do not have to assign all signals. For example, to exit cleanly from a ^C:

```\$SIG{'INT'} = 'CLEANUP';

sub CLEANUP {
print "Caught Interrupt (^C), Aborting\n";
exit(1);
}

```

There are two special “routines” for signals called DEFAULT and IGNORE. DEFAULT erases the current assignment, restoring the default value of the signal. IGNORE causes the signal to be ignored. In general, you don’t need to remember these as you can emulate their functionality with standard programming features. DEFAULT can be emulated by deleting the signal from the array and IGNORE can be emulated by any undeclared subroutine.

In 5.001, the \$SIG{__WARN__} and \$SIG{__DIE__} handlers may be used to intercept die() and warn(). For example, here’s how you could promote unitialized variables to trigger a fatal rather merely complaining:

```
#!/usr/bin/perl -w

require 5.001;

\$SIG{__WARN__} = sub {
if (\$_[0] =~ /uninit/) {
die [email protected];
} else {
warn [email protected];
}
};

```

## Perl DBI

### Perl DBI Example

The DBI module enables your Perl applications to access

multiple database types transparently. You can connect to

MySQL, MSSQL, Oracle, Informix, Sybase, ODBC etc. without

having to know the different underlying interfaces of each.

The API defined by DBI will work on all these database types

and many more.

What is DBI and DBD::Oracle and where can one get it from?

DBI (previously called DBperl) is a database independent interface module for Perl. It defines a set of methods, variables and conventions that provide a consistent database interface independent of the actual database being used.

DBD::Oracle is the Oracle specific module for DBI. It can be downloaded from CPAN.

What DBI drivers have I got?

In DBI you can programmatically discover what DBI drivers are installed.

```#!/usr/bin/perl -w

require DBI;

my @drivers = DBI->available_drivers;

print join(", ", @drivers), "n";

```

Example:

```use strict;

use DBI;

my \$dbh = DBI->connect( 'dbi:Oracle:orcl',

{

RaiseError => 1,

AutoCommit => 0

}

) || die "Database connection not made: \$DBI::errstr";

my \$sql = qq{ CREATE TABLE employees ( id INTEGER NOT NULL,

name VARCHAR2(128),

position VARCHAR2(128),

) };

\$dbh->do( \$sql );

\$dbh->disconnect();

```

SYBASE

Sybperl implements three Sybase extension modules to perl (version 5.002 or higher). Sybase::DBlib adds a subset of the Sybase DB-Library API. Sybase::CTlib adds a subset of the Sybase CT-Library (aka the Client Library) API. Sybase::Sybperl is a backwards compatibility module (implemented on top of Sybase::DBlib) to enable scripts written for sybperl 1.0xx to run with Perl 5. Using both the Sybase::Sybperl and Sybase::DBlib modules explicitly in a single script is not garanteed to work correctly.

The general usage format for both Sybase::DBlib and Sybase::CTlib is this:

```use Sybase::DBlib;

# Allocate a new connection, usually refered to as a database handle

# Set an attribute for this dbh:

\$dbh->{UseDateTime} = TRUE;

# Call a method with this dbh:

\$dbh->dbcmd(sql code);

```

The DBPROCESS or CS_CONNECTION that is opened with the call to new() is automatically closed when the \$dbh goes out of scope:

```sub run_a_query {

my \$dbh = new Sybase::CTlib \$user, \$passwd;

my @dat = \$dbh->ct_sql("select * from sysusers");

return @dat;

}

# The \$dbh is automatically closed when we exit the subroutine.

```

Sybase::DBlib

A generic perl script using Sybase::DBlib would look like this:

```use Sybase::DBlib;

\$dbh = new Sybase::DBlib 'sa', \$pwd, \$server, 'test_app';

\$dbh->dbcmd("select * from sysprocessesn");

\$dbh->dbsqlexec;

\$dbh->dbresults;

while(@data = \$dbh->dbnextrow)

{

.... do something with @data ....

}

```

\$dbh = Sybase::DBlib->dbopen([\$server [, \$appname, [{attributes}] ]])

\$status = \$dbh->dbuse(\$database)

Executes “use database \$database” for the connection \$dbh.

\$status = \$dbh->dbcmd(\$sql_cmd)

Appends the string \$sql_cmd to the current command buffer of this connection.

\$status = \$dbh->dbsqlexec

Sends the content of the current command buffer to the dataserver for execution. See the DB-library documentation for a discussion of return values.

\$status = \$dbh->dbresults

Retrieves result information from the dataserver after having executed dbsqlexec().

\$status = \$dbh->dbcancel

Cancels the current command batch.

\$status = \$dbh->dbcanquery

Cancels the current query within the currently executing command batch.

\$dbh->dbfreebuf

Free the command buffer (required only in special cases – if you don’t know what this is you probably don’t need it đź™‚

\$dbh->dbclose

Force the closing of a connection. Note that connections are automatically closed when the \$dbh goes out of scope.

Returns TRUE if the DBPROCESS has been marked DEAD by DBlibrary.

\$status = \$dbh->DBCURCMD

Returns the number of the currently executing command in the command batch. The first command is number 1.

\$status = \$dbh->DBMORECMDS

Returns TRUE if there are additional commands to be executed in the current command batch.

\$status = \$dbh->DBCMDROW

Returns SUCCEED if the current command can return rows.

\$status = \$dbh->DBROWS

Returns SUCCEED if the current command did return rows

\$status = \$dbh->DBCOUNT

Returns the number of rows that the current command affected.

\$row_num = \$dbh->DBCURROW

Returns the number (counting from 1) of the currently retrieved row in the current result set.

\$status = \$dbh->dbhasretstat

Did the last executed stored procedure return a status value? dbhasretstats must only be called after dbresults returns NO_MORE_RESULTS, ie after all the selet, insert, update operations of he sored procedure have been processed.

\$status = \$dbh->dbretstatus

Retrieve the return status of a stored procedure. As with dbhasretstat, call this function after all the result sets of the stored procedure have been processed.

\$status = \$dbh->dbnumcols

How many columns are in the current result set.

\$status = \$dbh->dbcoltype(\$colid)

What is the column type of column \$colid in the current result set.

\$status = \$dbh->dbcollen(\$colid)

What is the length (in bytes) of column \$colid in the current result set.

\$string = \$dbh->dbcolname(\$colid)

What is the name of column \$colid in the current result set.

@dat = \$dbh->dbretdata[\$doAssoc])

Retrieve the value of the parameters marked as ‘OUTPUT’ in a stored procedure. If \$doAssoc is non-0, then retrieve the data as an associative array with parameter name/value pairs.

## Perl OOP

### Perl OOP

Why Object Oriented approach?

A major factor in the invention of Object-Oriented approach is to remove some of the flaws encountered with the procedural approach. In OOP, data is treated as a critical element and does not allow it to flow freely. It bounds data closely to the functions that operate on it and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. A major advantage of OOP is code re-usability.

Some important features of Object Oriented programming are as follows:

• Emphasis on data rather than procedure
• Programs are divided into Objects
• Data is hidden and cannot be accessed by external functions
• Objects can communicate with each other through functions
• New data and functions can be easily added whenever necessary
• Follows bottom-up approach

Concepts of OOP:

• Objects
• Classes
• Data Abstraction and Encapsulation
• Inheritance
• Polymorphism

Briefly on Concepts:

Objects

Objects are the basic run-time entities in an object-oriented system. Programming problem is analyzed in terms of objects and nature of communication between them. When a program is executed, objects interact with each other by sending messages. Different objects can also interact with each other without knowing the details of their data or code.

Classes

A class is a collection of objects of similar type. Once a class is defined, any number of objects can be created which belong to that class.

Data Abstraction and Encapsulation

Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes.

Storing data and functions in a single unit (class) is encapsulation. Data cannot be accessible to the outside world and only those functions which are stored in the class can access it.

Inheritance

Inheritance is the process by which objects can acquire the properties of objects of other class. In OOP, inheritance provides reusability, like, adding additional features to an existing class without modifying it. This is achieved by deriving a new class from the existing one. The new class will have combined features of both the classes.

Polymorphism

Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing Inheritance.

Object-Oriented Programming has the following advantages over conventional approaches:

• OOP provides a clear modular structure for programs which makes it good for defining abstract datatypes where implementation details are hidden and the unit has a clearly defined interface.
• OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones.
• OOP provides a good framework for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces.

Perl Package

• To create a class in Perl, we first create a

package.

• A package (module) is a module of variables and

subroutines, which can be re-used over and over again.

• They provide a separate namespace within a Perl

program that keeps subroutines and variables from

conflicting with those in other packages.

To declare a class named Person in Perl we do:

package Person;

• The scope of the package definition extends to the

end of the file

• or until another package keyword is encountered.
##### Perl Methods

A method (subroutine) is a way of accessing objects. In

Perl, a method is just a subroutine defined within a

particular package. So to define a method to print our

Person object, we do:

```sub print {

my (\$self) = @_; ## creating reference

#print Person info

printf( "Name:%s %snn", \$self->firstName, \$self->lastName );

}

```

The subroutine print is now associated with the package

Person. To call the method print on a Person object, we

use the Perl “arrow” notation. If the variable \$mike

contains a Person object, we would call print on that

object by writing:

\$mike->print();

When the object method is invoked, a reference to the

object is passed in along with any other arguments

(including class name). This is important since the

method now has access to the object on which it is to

operate.

##### How do we create object?
• To create an instance of a class (an object) we need

an object constructor.

• This constructor is a method defined within the

package.

• Most programmers choose to name this object

constructor method new, but in Perl one can use any

name.

• One can use any kind of Perl variable as an object

in Perl.

• Most Perl programmers choose either

references to arrays or hashes.

Let’s create our constructor for our Person class using

a Perl hash reference;

```package Person;

sub new {

my \$self = {

_firstName => undef,

_lastName  => undef,

_ssn       => undef,

_salary    => undef,

_dept      => undef

};

bless \$self, 'Person';

return \$self;

}

sub print {

my (\$self) = @_; ## creating reference

#print Person info

printf( "Name:%s %snn", \$self->firstName, \$self->lastName );

}

```
• We created a subroutine (method) called new

associatedwith the package Person.

• Other method is print (as discussed earlier).
• The entries of the hash reference \$self become the

attributes of our object. We then use the bless function

on the hash reference.

• The bless function takes two arguments: a reference

to the variable to be marked and a string containing the

name of the class. This indicates that the variable now

belongs to the class Person.

To create an instance of our Person object:

my \$mike = new Person();

We have not defined accessor methods or done any error

checking on the input values or keys or the anonymous

hash reference, but we have the start of a Perl Person

OO framework. To make our constructor more flexible and

to make our class inheritable (more on that later), we

can define it to use the \$class variable to bless the

hash reference.

```#constructor

sub new {

my (\$class) = @_;

my \$self = {

_firstName => undef,

_lastName  => undef,

_ssn       => undef,

_salary    => undef,

_dept      => undef

};

bless \$self, \$class;

return \$self;

}

```

Other object-oriented languages have the concept of

security of data to prevent a programmer from changing

an object data directly and so provide accessor methods

to modify object data. Perl does not have private

variables but we can still use the concept of accessor

methods and ask programmers to not mess with our object

innards.

For our Person class, we should provides accessor

methods for our object attributes; name, address, title,

ssn,salary,dept.

```package Person;

use strict;

#constructor

sub new {

my (\$class) = @_;

my \$self = {

_firstName => undef,

_lastName  => undef,

_ssn       => undef,

_salary    => undef,

_dept      => undef

};

bless \$self, \$class;

return \$self;

}

#accessor method for Person first name

sub firstName {

my ( \$self, \$firstName ) = @_;

\$self->{_firstName} = \$firstName if defined (\$firstName);

return \$self->{_firstName};

}

#accessor method for Person last name

sub lastName {

my ( \$self, \$lastName ) = @_;

\$self->{_lastName} = \$lastName if defined(\$lastName);

return \$self->{_lastName};

}

my ( \$self, \$address ) = @_;

}

#accessor method for Person social security number

sub ssn {

my ( \$self, \$ssn ) = @_;

\$self->{_ssn} = \$ssn if defined(\$ssn);

return \$self->{_ssn};

}

sub salary {

my ( \$self, \$salary ) = @_;

\$self->{_salary} = \$salary if defined(\$salary);

return \$self->{_salary};

}

sub dept {

my ( \$self, \$dept ) = @_;

\$self->{_dept} = \$dept if defined(\$dept);

return \$self->{_dept};

}

sub print {

my (\$self) = @_;

#print Person info

printf( "Name:%s %snn", \$self->firstName, \$self->lastName );

}

1;

```
##### Making Objects

Object-oriented programming sometimes involves

inheritance. Inheritance simply means allowing one class

called the Child to inherit methods and attributes from

another, called the Parent, so you don’t have to write

the same code again and again. For example, we can have

a class Employee which inherits from Person. This is

referred to as an “isa” relationship because an employee

is a person. Perl has a special variable, @ISA, to help

with this.

@ISA governs (method) inheritance. So to create a new

Employee class that will inherit methods and attributes

from our Person class, we simply code:

```# class Employee

package Employee;

use Person;

use strict;

our @ISA = qw(Person);    # inherits from Person

```

What we have done is load the Person class and declare

that Employee class inherits methods from it. We have

declared no methods for Employee but an Employee object

will behave just like a Person object. We should be able

to write code:

```#create Employee class instance

my \$mike =  new Employee();

#set object attributes

\$mike->firstName('mike');

\$mike->lastName('Weis');

```

without any other changes.

```# class Employee

package Employee;

use Person;

use strict;

our @ISA = qw(Person);    # inherits from Person

#constructor

sub new {

my (\$class) = @_;

#call the constructor of the parent class, Person.

my \$self = \$class->SUPER::new();

\$self->{_id}   = undef;

\$self->{_title} = undef;

bless \$self, \$class;

return \$self;

}

#accessor method for  id

sub id {

my ( \$self, \$id ) = @_;

\$self->{_id} = \$id if defined(\$id);

return ( \$self->{_id} );

}

#accessor method for  title

sub title {

my ( \$self, \$title ) = @_;

\$self->{_title} = \$title if defined(\$title);

return ( \$self->{_title} );

}

sub print {

my (\$self) = @_;

# we will call the print method of the parent class

\$self->SUPER::print;

}

1;

```

Looking at the code, you will notice that we have a new

method and a print method. Both the child class and its

parent class have the same method defined. We have

overridden the parent class’ methods with the ones from

the child. When those methods are called on an Employee

object, we will get the Employee class’ version of the

method. This concept of using the methods of an existing

object and modifying them is known as polymorphism.

Putting it together

So now that we have a complete set of classes, we can

write a small program to test them.

```use strict;

use warnings;

use diagnostics;

use Employee;

#create Employee class instance

my \$mike =  eval { new Employee(); }  or die ([email protected]);

#set object attributes

\$mike->firstName('mike');

\$mike->lastName('Weis');

\$mike->id(0731034);

\$mike->title('Perl Programmer');

#diplay Employee info

\$mike->print();

```

Let’s execute our code and see the output:

\$ ./test.pl

Name:mike Weis

Jersey City, NJ 665030

• ## Perl File Operations

### Perl File operations

Variables which represent files are called “file handles”, and they are handled differently from other variables. They do not begin with any special character — they are just plain words. By convention, file handle variables are written in all upper case, like FILE_OUT or SOCK. The file handles are all in a global namespace, so you cannot allocate them locally like other variables. File handles can be passed from one routine to another like strings (detailed below).

The standard file handles STDIN, STDOUT, and STDERR are automatically opened before the program runs. Surrounding a file handle with <> is an expression that returns one line from the file including the “n” character, so returns one line from standard input. The <> operator returns undef when there is no more input. The “chop” operator removes the last character from a string, so it can be used just after an input operation to remove the trailing “n”. The “chomp” operator is similar, but only removes the character if it is the end-of-line character.

```\$line = ; ## read one line from the STDIN file handle

chomp(\$line); ## remove the trailing "n" if present

```

File Open and Close

The “open” and “close” operators operate as in C to connect a file handle to a filename in the file system.

```open(F1, "filename"); ## open "filename" for reading as file handle F1

open(F2, ">filename"); ## open "filename" for writing as file handle F2

open(F3, ">>appendtome") ## open "appendtome" for appending

close(F1); ## close a file handle

```

Open can also be used to establish a reading or writing connection to a separate process launched by the OS. This works best on Unix.

```open(F4, "ls -l |"); ## open a pipe to read from an ls process

open(F5, "| mail \$addr"); ## open a pipe to write to a mail process

```

Passing commands to the shell to launch an OS process in this way can be very convenient, but it’s also a famous source of security problems in CGI programs. When writing a CGI, do not pass a string from the client side as a filename in a call to open().

Open returns undef on failure, so the following phrase is often to exit if a file can’t be opened. The die operator prints an error message and terminates the program.

```open(FILE, \$fname) || die "Could not open \$fnamen";

```

In this example, the logical-or operator || essentially builds an if statement, since it only evaluates the second expression if the first if false. This construct is a little strange, but it is a common code pattern for Perl error handling.

Input Variants

In a scalar context the input operator reads one line at a time. In an array context, the input operator reads the entire file into memory as an array of its lines… @a = ; ## read the whole file in as an array of lines

This syntax can be dangerous. The following statement looks like it reads just a single line, but actually the left hand side is an array context, so it reads the whole file and then discards all but the first line….

my(\$line) = ;

The behavior of also depends on the special global variable \$/ which is the current the end-of-line marker (usually “n”). Setting \$/ to undef causes to read the whole file into a single string.

```\$/ = undef;

\$all = ; ## read the whole file into one string

```

You can remember that \$/ is the end-of-line marker because “/” is used to designate separate lines of poetry. I thought this mnemonic was silly when I first saw it, but sure enough, I now remember that \$/ is the end-of-line marker.

Print Output

Print takes a series of things to print separated by commas. By default, print writes to the STDOUT file handle.

```print "Woo Hoon"; ## print a string to STDOUT

\$num = 42;

\$str = " Hoo";

print "Woo", \$a, " bbb \$num", "n"; ## print several things

```

An optional first argument to print can specify the destination file handle. There is no comma after the file handle, but I always forget to omit it.

```print FILE "Here", " there", " everywhere!", "n";

```

File Processing Example

As an example, here’s some code that opens each of the files listed in the @ARGV array, and reads in and prints out their contents to standard output…

```#!/usr/bin/perl -w

require 5.004;

## Open each command line file and print its contents to standard out

foreach \$fname (@ARGV) {

open(FILE, \$fname) || die("Could not open \$fnamen");

while(\$line = ) {

print \$line;

}

close(FILE);

}

```

The above uses “die” to abort the program if one of the files cannot be opened. We could use a more flexible strategy where we print an error message for that file but continue to try to process the other files. Alternately we could use the function call exit(-1) to exit the program with an error code. Also, the following shift pattern is a common alternative way to iterate through an array…

```while(\$fname = shift(@ARGV)) {...
/pre>```

## Perl Regular Expressions

### Perl Regular Expressions

```

Metacharacters

char meaning

^      beginning of string

\$      end of string

.      any character except newline

*      match 0 or more times

+      match 1 or more times

?      match 0 or 1 times; or: shortest match

|      alternative

( )    grouping; "storing"

[ ]    set of characters

{ }    repetition modifier

quote or special

```
```Repetition

a*     zero or more a's

a+     one or more a's

a?     zero or one a's (i.e., optional a)

a{m}   exactly m a's

a{m,}  at least m a's

a{m,n} at least m but at most n a's repetition?

t     tab

n     newline

r     return (CR)

xhh   character with hex. code hh

b     "word" boundary

B     not a "word" boundary

w     matches any single character classified as a

"word" character (alphanumeric or _)

W     matches any non-"word" character

s     matches any whitespace character (space, tab, newline)

S     matches any non-whitespace character

d     matches any digit character, equiv. to [0-9]

D     matches any non-digit character

[characters] matches any of the characters in the sequence

[x-y]        matches any of the characters from x to y

(inclusively) in the ASCII code

[-]         matches the hyphen character -

[n]         matches the newline; other single character

denotations with  apply normally, too

```

Examples

How do I extract everything between a the words “start” and “end”?

\$mystring = “The start text always precedes the end of the end text.”;

if(\$mystring =~ m/start(.*)end/) {

print \$1;

}

How do I extract a complete number, like the year?

if(\$mystring =~ m/(d+)/) {

print “The first number is \$1.”;

}

# find word that is bolded

# returns: \$1 = ‘text’

\$line = “This is some text with HTML and “;

\$line =~ m/(.*)/i;

## Perl Subroutine

### Perl Subroutine

```sub mysubroutine

{

print "Not a very interesting routinen";

print "This does the same thing every timen";

}

```

regardless of any parameters that we may want to pass to it. All of the following will work to call this subroutine. Notice that a subroutine is called with an & character in front of the name:

```&mysubroutine;		# Call the subroutine

&mysubroutine(\$_);	# Call it with a parameter

&mysubroutine(1+2, \$_);	# Call it with two parameters

```

#### Parameters

In the above case the parameters are acceptable but ignored. When the subroutine is called any parameters are passed as a list in the special @_ list array variable. This variable has absolutely nothing to do with the \$_ scalar variable. The following subroutine merely prints out the list that it was called with. It is followed by a couple of examples of its use.

```sub printargs

{

print "@_n";

}

&printargs("perly", "king");	# Example prints "perly king"

```

Just like any other list array the individual elements of @_ can be accessed with the square bracket notation:

```sub printfirsttwo

{

print "Your first argument was \$_[0]n";

print "and \$_[1] was your secondn";

}

```

Again it should be stressed that the indexed scalars \$_[0] and \$_[1] and so on have nothing to with the scalar \$_ which can also be used without fear of a clash.

Returning values

Result of a subroutine is always the last thing evaluated. This subroutine returns the maximum of two input parameters. An example of its use follows.

```sub maximum

{

if (\$_[0] > \$_[1])

{

\$_[0];

}

else

{

\$_[1];

}

}

\$biggest = &maximum(37, 24);	# Now \$biggest is 37

```

The &printfirsttwo subroutine above also returns a value, in this case 1. This is because the last thing that subroutine did was a print statement and the result of a successful print statement is always 1.

#### Local variables

The @_ variable is local to the current subroutine, and so of course are \$_[0], \$_[1], \$_[2], and so on. Other variables can be made local too, and this is useful if we want to start altering the input parameters. The following subroutine tests to see if one string is inside another, spaces not withstanding. An example follows.

```sub inside

{

local(\$a, \$b);                  # Make local variables

(\$a, \$b) = (\$_[0], \$_[1]);      # Assign values

\$a =~ s/ //g;                   # Strip spaces from

\$b =~ s/ //g;                   # local variables

(\$a =~ /\$b/ || \$b =~ /\$a/);     # Is \$b inside \$a

# or \$a inside \$b?

}

&inside("lemon", "dole money");		# true

```

In fact, it can even be tidied up by replacing the first two lines with

local(\$a, \$b) = (\$_[0], \$_[1]);

## Perl References

### Perl References

I’m happiest writing Perl code that does not use references because they always give me a mild headache. Here’s the short version of how they work. The backslash operator () computes a reference to something. The reference is a scalar that points to the original thing. The ‘\$’ dereferences to access the original thing. Suppose there is a string…

\$str = “hello”; ## original string

And there is a reference that points to that string…

\$ref = \$str; ## compute \$ref that points to \$str

The expression to access \$str is \$\$ref. Essentially, the alphabetic part of the variable, ‘str’, is replaced with the dereference expression ‘\$ref’…

print “\$\$refn”; ## prints “hello” — identical to “\$strn”;

Here’s an example of the same principle with a reference to an array…

@a = (1, 2, 3); ## original array

\$aRef = @a; ## reference to the array

print “a: @an”; ## prints “a: 1 2 3”

print “a: @\$aRefn”; ## exactly the same

Curly braces { } can be added in code and in strings to help clarify the stack of @, \$, …

print “a: @{\$aRef}n”; ## use { } for clarity

Here’s how you put references to arrays in another array to make it look two dimensional…

@a = (1, 2, 3); @b = (4, 5, 6);

@root = (@a, @b);

print “a: @an”; ## a: (1 2 3)

print “a: @{\$root[0]}n”; ## a: (1 2 3)

print “b: @{\$root[1]}n”; ## b: (4 5 6)

scalar(@root) ## root len == 2

scalar(@{\$root[0]}) ## a len: == 3

For arrays of arrays, the [ ] operations can stack together so the syntax is more C like…

\$root[1][0] ## this is 4

## Perl if else

### The if…else Statement

This statement uses a relational expression to check the validity of a condition and execute a set of statements enclosed in braces. It returns a Boolean value, true or false, according to the validity of the condition. The syntax of the if…else statement is:

```if(condition)

{

block of statement(s);

}

else

{

block of statement(s);

}

```

In this syntax, condition is a relational expression. If the result of this expression is true, then the block of statements following the if statement is executed. Otherwise, the block of statements following the else statement is executed.

In Perl, unlike other languages, all loops and conditional constructs require statements to be enclosed in braces, even for single statements.

```#! /usr/bin/perl

print "Enter a value for a: ";

\$a = <>;

print "Enter a value for b: ";

\$b  = <>;

if (\$a>\$b)

{

print "a is greater than bn";

}

else

{

print "b is greater than an";

}

```

In this example, the if clause checks whether \$a is greater than \$b. If the value of \$a is greater than \$b, then the result is: a is greater than b. Otherwise, the control transfers to the code following the else clause and the statement associated with the else clause is printed as a result.

The if…elsif…else Statement

This statement is used when there is more than one condition to be checked. The syntax of the if…elsif…else statement is:

```if (condition)

{

block of statement(s);

}

elsif (condition)

{

block of statement(s);

}

else

{

block of statement(s);

}

```

In this syntax, if the condition associated with the if clause is false, the control transfers to elsif clause that checks for the next condition. The code associated with elsif clause is executed only if the condition is true or the code associated with the else clause is executed.

```#! /usr/bin/perl

print "Enter the score of a student: ";

\$score = <>;

if(\$score>=90)

{

print "Excellent Performancen";

}

elsif(\$score>=70 && \$score<90)

{

print "Good Performancen";

}

else

{

print "Try hardn";

}

```

## Perl Loop

### The Loop Statements

Different loop statements in perl…

• The for Loop
• The foreach Loop
• The while Loop
• The do-while Loop
• The until Loop

The process of executing a code block repetitively is known as

iteration. To perform iteration in applications, use the loop

statements, such as for and while.

The loop statements check a condition and repetitively execute the

enclosed statements until the condition is true. The loop

terminates only when the condition becomes invalid.

The for Loop

This loop is used to execute a given set of statements for a fixed

number of times. The syntax of the for loop is:

```for(initialization;testing;updation)

{

block of statement(s);

}

```

In these statements:

initialization: Is the code to declare and initialize the

loop counter. Loop counter is a variable to keep a check on the

number of iterations. Initialization happens only once before the

beginning of the loop.

testing: Is the code, which specifies the condition to

control the number of iterations. The loop executes until the

result of testing is true. When the condition becomes false, the

control passes to the statement following the loop.

updation: Is the code to modify the loop counter after each

iteration. It can increment or decrement the loop counter,

according to the program requirements. Updation occurs at the end

of the loop.

block of statement(s): Is the code to be executed

iteratively. This code must be enclosed within the curly braces.

Note The three expressions for initialization, condition, and

updation are optional. If you leave the condition expression empty,

the for loop will be an infinite loop.

```#! /usr/bin/perl

print "Enter a digit to create its table: ";

\$a = <>;

chomp(\$a);

for(\$b=1;\$b<=10;\$b++)

{

print \$a.' x '.\$b.' = '. \$a*\$b."n";

}

```
• \$b=1 is the initialization statement, which initializes the

loop counter \$b to 1.

• \$b<=10 is the testing statement, which checks whether the value stored in \$b is less than or equal to 10.
• \$b++ is the updation statement, which increments the value of

\$b by 1.

The Nested for Loop

A for loop contained inside another for loop is called a nested for

loop. This is used when the data is to be stored and printed in a

tabular format having multiple rows and columns.

```#! /usr/bin/perl

for(\$a=0;\$a<=9;\$a++){

for(\$b=0;\$b<=\$a;\$b++){

print "*";

}

print "n";

}

```

In this program:

• The outer loop works until the value of \$a is less than or

equal to 9.

• The inner loop works until the value of \$b is less than or

equal to the value of \$a.

• The newline character n is used to enter a newline after every

row.

Note The nested for loops are used with multidimensional arrays.

The foreach Loop

This loop operates on arrays. An array stores multiple related

values in a row that can be accessed easily using the foreach loop.

The syntax of the foreach loop is:

```foreach \$var_name (@array_name)

{

block of statement(s);

}

```

In this syntax:

• @array_name is the array whose elements are accessed using the

foreach loop.

• \$var_name is the scalar variable that stores the value of

element of @array_name for each iteration.

• This loop is repeated for all the elements in the array. The

code used for the foreach loop is:

```#! /usr/bin/perl

@names = ("George", "Jack", "Davis");

foreach \$word(@names)

{

print "\$wordn";

}

```

This example, when executed, prints values of all the elements in

the @names array one-by-one using the foreach loop. The output of

the example is shown in Figure 4-5:

The while Loop

There may be situations when you do not know the number of times a

loop is to be executed. For example, an application accepts and

stores the scores of students in a class, and you do not know the

number of students in a class. In this example, you can use the

while loop.

The while loop executes as long as the condition specified is true.

The condition can be any valid relational expression, which returns

true or false.

This loop is also known as Pre-Check or Pre-Tested Looping

Construct because the condition is checked before executing the

statement(s) in the block.

The syntax of the while loop is:

```while (condition)

{

block of statement(s);

}

```

In these statements, block of statement(s) is executed only if the

condition is true.

Note The code block must be enclosed within curly braces.

```#! /usr/bin/perl

\$a = 1;

while (\$a <= 10)

{

print "\$an";

\$a++;

}

```

In this example:

• \$a, the loop counter is initialized to 1.
• The condition checks whether \$a is less than or equal to 10.
• The value of \$a is incremented by 1 in each iteration using the

post increment operator (++).

• The loop prints the numbers from 1 to 10 until the value of \$a is less than or equal to 10. When \$a is incremented to 11, the condition results in false, and the loop terminates.

The do-while Loop

The do-while loop is used when you want to execute a code block at

least once unconditionally, and then iteratively on the basis of a

condition.

In this loop, condition is tested at the end of the loop. Because

of this, this loop is also known as Post-Check or Post Tested

Looping Construct.

The syntax of the do-while loop is:

```do

{

block of statement(s);

}

while (condition);

```

```#! /usr/bin/perl

\$a = 2;

do

{

print "\$an";

\$a+=2;

} while (\$a<=20);

```

In this example:

• \$a, the loop counter is initialized to 2.
• The loop prints the value of \$a and also increments it by 2.
• The condition associated with while tests whether the value of

\$a is less than or equal to 20.

• The loop prints even numbers until the value of \$a is less than

or equal to 20. When \$a is equal to 22, the loop terminates.

The until Loop

In case of the while loop, the code that follows condition is

executed only if the condition is true. In the case of the until

loop, code associated with the condition is executed only if the

condition is false. The syntax of the until loop is:

```until(condition)

{

block of statement(s);

}

```

In this syntax, the block of statement(s) is executed only when the

condition returns false.

```#! /usr/bin/perl

\$a = 1;

until(a == 11)

{

print \$a."n";

\$a++;

}

```

In this program:

• \$a, the loop counter is initialized to 1.
• The condition checks whether \$a is equal to 11.
• The loop prints and increments the value of \$a.
• The condition returns false until \$a is less than 11, and the

code in the loop prints from 1 to 10. The moment \$a is equal to 11,

the condition is met and loop is terminated.

• ## Perl ARGV

### @ARGV and %ENV

The built-in array @ARGV contains the command line arguments for a Perl program. The following run of the Perl program critic.pl will have the ARGV array (“-poetry”, “poem.txt”).

unix% perl critic.pl -poetry poem.txt

%ENV contains the environment variables of the context that launched the Perl program.

@ARGV and %ENV make the most sense in a Unix environment.

So for example you have a script like test.pl

```#!/usr/bin/perl

use strict;

my \$column=\$ARGV[0];

my \$database=\$ARGV[1];

------run the program now---

\$./test.pl ssn employees

```

in above example we are passing two values as commandline arguments. so \$column will have “ssn” and \$database will have “employees”.
Note: Pass values in quoutes if values have spaces.

## Perl Hash Maps

### Perl Hash Maps/associative arrays

ASSIGNING HASH VALUES

• hash tables consist of key/value pairs
• every key is followed by a value

values can be assigned to hash tables as

```%states=

```

We can also use => operator to identify the

key to the left, and the value to the right; if the => operator

encounters bare words in key positions, they will be automatically

quoted (note “New York”, however, which consists of two words

and MUST be quoted

```%states=

```

In above example California is key and Sacromento is value.

Similarily Wisconsin is key and Madison is value.

Printing:

```print "Capital of California is " . \$states{"California"} . "nn";

```

printing all values(using for loop):

```#!/usr/bin/perl

%states=

foreach my \$keys(keys %states)

{

print "KEY:\$keys VALUE:\$states{\$keys}n";

}

output

KEY:New York VALUE:Albany

KEY:California VALUE:Sacramento

```
• ## Perl Arrays

### Arrays @

Array constants are specified using parenthesis ( ) and the elements are separated with

commas. Perl arrays are like lists or collections in other languages since they can grow

and shrink, but in Perl they are just called “arrays”. Array variable names begin with the

at-sign (@). Unlike C, the assignment operator (=) works for arrays — an independent copy

of the array and its elements is made. Arrays may not contain other arrays as elements.

Perl has sort of a “1-deep” mentality. Actually, it’s possible to get around the 1-deep

constraint using “references”, but it’s no fun. Arrays work best if they just contain

scalars (strings and numbers). The elements in an array do not all need to be the same

type.

```@array = (1, 2, "hello");  ## a 3 element array

@empty = ();               ## the array with 0 elements

\$x = 1;

\$y = 2;

@nums = (\$x + \$y, \$x - \$y);

## @nums is now (3, -1)

```

Just as in C, square brackets [ ] are used to refer to elements, so \$a[6] is the element

at index 6 in the array @a. As in C, array indexes start at 0. Notice that the syntax to

access an element begins with ‘\$’ not ‘@’ — use ‘@’ only when referring to the whole

array (remember: all scalar expressions begin with \$).

```@array = (1, 2, "hello", "there");

\$array[0] = \$array[0] + \$array[1];## \$array[0] is now 3

```

Perl arrays are not bounds checked. If code attempts to read an element outside the array

size, undef is returned. If code writes outside the array size, the array grows

automatically to be big enough. Well written code probably should not rely on either of

those features.

```@array = (1, 2, "hello", "there");

\$sum = \$array[0] + \$array[27];

## \$sum is now 1, since \$array[27] returned undef

\$array[99] = "the end";

## array grows to be size 100

```

When used in a scalar context, an array evaluates to its length. The “scalar” operator

will force the evaluation of something in a scalar context, so you can use scalar() to get

the length of an array. As an alternative to using scalar, the expression \$#array is the

index of the last element of the array which is always one less than the length.

```@array = (1, 2, "hello", "there");

\$len = @array;

## \$len is now 4 (the length of @array)

\$len = scalar(@array);

## same as above, since \$len represented a scalar

## context anyway, but this is more explicit

```
```@letters = ("a", "b", "c");

\$i = \$#letters;## \$i is now 2

```

That scalar(@array) is the way to refer to the length of an array is not a great moment in

the history of readable code. At least I haven’t showed you the even more vulgar forms

such as (0 + @a).

The sort operator (sort @a) returns a copy of the array sorted in ascending alphabetic

order. Note that sort does not change the original array. Here are some common ways to sort…

```(sort @array)

## sort alphabetically, with uppercase first

(sort {\$a <=> \$b} @array)

## sort numerically

(sort {\$b cmp \$a} @array)

## sort reverse alphabetically

(sort {lc(\$a) cmp lc(\$b)} @array)

## sort alphabetically, ignoring case (somewhat inefficient)

```

The sort expression above pass a comparator function {…} to the sort operator, where the

special variables \$a and \$b are the two elements to compare — cmp is the built-in string

compare, and <=> is the built-in numeric compare.

There’s a variant of array assignment that is used sometimes to assign several variables

at once. If an array on the left hand side of an assignment operation contains the names

of variables, the variables are assigned the corresponding values from the right hand

side.

(\$x, \$y, \$z) = (1, 2, “hello”, 4);

## assigns \$x=1, \$y=2, \$z=”hello”, and the 4 is discarded

This type of assignment only works with scalars. If one of the values is an array, the

wrong thing happens (see “flattening” below).

These handy operators will add or remove an element from an array. These operators change

the array they operate on…

Operating at the “front” (\$array[0]) end of the array…

shift(array)
returns the frontmost element and removes it from the array. Can be used

in a loop to gradually remove and examine all the elements in an array left to right. The

foreach operator, below, is another way to examine all the elements.

unshift(array, elem)
inserts an element at the front of the array. Opposite of shift.

Operating at the “back” (\$array[\$len-1]) end of the array…

pop(array)
returns the endmost element (right hand side) and removes it from the

array.

push(array, elem)
adds a single element to the end of the array. Opposite of pop.

splice(array, index, length, array2)
removes the section of the array defined by index

and length, and replaces that section with the elements from array2. If array2 is omitted,

splice()
simply deletes. For example, to delete the element at index \$i from an array, use

splice(@array, \$i, 1).

## Perl Operators

### Perl Operators

In Perl, the comparison operators are divided into two classes:

• Comparison operators that work with numbers
• Comparison operators that work with strings

Integer-Comparison Operators

```Operator Description

<        Less than

>        Greater than

==       Equal to

<=       Less than or equal to

>=       Greater than or equal to

!=       Not equal to

<=> Comparison returning 1, 0, or -1

```

Each of these operators yields one of two values:

• True, or nonzero
• False, or zero

The <=> operator is a special case. Unlike the other integer comparison operators, <=> returns one of three values:

• 0, if the two values being compared are equal
• 1, if the first value is greater
• -1, if the second value is greater

String-Comparison Operators

For every numeric-comparison operator, Perl defines an equivalent string-comparison operator.

```String operator Comparison operation

lt              Less than

gt              Greater than

eq              Equal to

le              Less than or equal to

ge              Greater than or equal to

ne              Not equal to !=

cmp             Compare, returning 1, 0, or -1

```

Example

```#!/usr/bin/perl

\$a="coding-school.com";

\$b="www.coding-school.com";

if(\$a eq \$b)

{

print "Both are same";

}

else

{

print "Both are different";

}

```

## Perl List

### List

A list is a sequence of scalar values enclosed in parentheses. The following is a simple example of a list:

(1, 5.3, “hello”, 2)

This list contains four elements, each of which is a scalar value: the numbers 1 and 5.3, the string hello, and the number 2.

Lists can be as long as needed, and they can contain any scalar value. A list can have no elements at all, as follows:

()

This list also is called an empty list.

NOTE

A list with one element and a scalar value are different entities. For example, the list

(43.2)

and the scalar value

43.2

are not the same thing. This is not a limitation because one can be converted to or assigned to the other.

## Perl Scalars

### Perl Scalars

The most basic kind of variable in Perl is the scalar variable.

Scalar variables hold both strings and numbers, and are remarkable in

that strings and numbers are completely interchangable. For example,

the statement

\$priority =10;

sets the scalar variable \$priority to 10, but you can also assign a string

to exactly the same variable:

\$priority = ‘high’;

Perl also accepts numbers as strings, like this:

\$priority = ’10’;

\$default = ‘0010’;

and can still cope with arithmetic and other operations quite happily.

In general variable names consists of numbers, letters and underscores, but

they should not start with a number and the variable \$_ is

special, as we’ll see later. Also, Perl is case sensitive, so

\$a and \$A are different.

#### Operations and Assignment

Perl uses all the usual C arithmetic operators:

 \$a = 1 + 2; # Add 1 and 2 and store in \$a \$a = 3 – 4; # Subtract 4 from 3 and store in \$a \$a = 5 * 6; # Multiply 5 and 6 \$a = 7 / 8; # Divide 7 by 8 to give 0.875 \$a = 9 ** 10; # Nine to the power of 10 \$a = 5 % 2; # Remainder of 5 divided by 2 ++\$a; # Increment \$a and then return it \$a++; # Return \$a and then increment it –\$a; # Decrement \$a and then return it \$a–; # Return \$a and then decrement it

and for strings Perl has the following among others:

 \$a = \$b . \$c; # Concatenate \$b and \$c \$a = \$b x \$c; # \$b repeated \$c times

To assign values Perl includes

 \$a = \$b; # Assign \$b to \$a \$a += \$b; # Add \$b to \$a \$a -= \$b; # Subtract \$b from \$a \$a .= \$b; # Append \$b onto \$a

Note that when Perl assigns a value with \$a = \$b it makes

a copy of \$b and then assigns that to \$a. Therefore the next time you change

\$b it will not alter \$a.

#### Interpolation

The following code prints apples and pears using concatenation:

\$a = ‘apples’;

\$b = ‘pears’;

print \$a.’ and ‘.\$b;

It would be nicer to include only one string in the final print statement,

but the line

print ‘\$a and \$b’;

can use the double quotes in place of the single quotes:

print “\$a and \$b”;

The double quotes force interpolation of any codes, including

interpreting variables. This is a much nicer than our original statement.

Other codes that are interpolated include special characters such as

newline and tab. The code n is a newline and

t is a tab.

## PHP Files

### PHP File handling

PHP includes a lot of built-in functions for handling files and directories. You can read, write, delete, and get lots of information on files thru the use of these functions. Note that before you start working with files, you have to make sure that you have the right permissions that will allow you to manipulate them. So while youâ€™re trying to figure out why you canâ€™t delete a file, it may be because the server doesnâ€™t allow you to do that.

The creation and removal of files are completed with two functions: â€śtouch()â€ť and â€śunlink()â€ť. â€śtouch()â€ť searches if a file exists, and if it doesnâ€™t, it creates one, according to the specified filename; â€śunlink()â€ť is used to remove the file passed on as an argument:

```touch(â€śnewinfo.txtâ€ť); //create a new file, if it doesnâ€™t already exist
```

Now that you know how to create a file, you should learn how to access it. This is done using the â€śfopen()â€ť function, with requires a string containing the file path and a string containing the mode in which the file is about to be opened, which tells â€śfopen()â€ť to open a file for reading, writing, or both. The complete list of the available modes can be found in the PHP documentation. â€śfopen()â€ť return an integer, also known as a file pointer, which should be assigned to a variable. This will be used later on to work with the opened file. If a file cannot be open for whatever reason, â€śfopen()â€ť returns FALSE. After youâ€™re done with the file, you should remember to close it with â€śfclose()â€ť, passing as an argument the file pointer.

```\$oldfp = fopen(â€śoldinfo.txtâ€ť, â€śrâ€ť); //opens a file for reading
if(!\$fp = fopen(â€śnewinfo.txtâ€ť, â€śwâ€ť)) //tries to open a file for writing
die(â€śError opening file!â€ť); //terminates execution if it cannot open the file
fclose(\$oldfp);
```

Reading from files is done with â€śfgets()â€ť, which reads data from a file until it reaches a new line â€śnâ€ť, an EOF (end-of-file), or a specified length, in this order. So if you specify 4096 bytes but â€śfgets()â€ť first reaches a new line, it stops further reading. You should know that after each reading or writing to a file, PHP automatically increments an index which holds the current position in the file. So if you have just opened a file, and then read 100 bytes, the next time you will want to read something else using the same file pointer, PHP will continue from where the 101st byte. The â€śfgetc()â€ť is similar to â€śfgets()â€ť, except that it returns only a single character from a file every time it is called. Because a character is always 1 byte in size, â€śfgetc()â€ť doesnâ€™t require a length argument.

```\$text = fgets(\$fp, 2000); //reads 2000 bytes at most
\$chr = fgetc(\$fp); //reads 1 byte only
```

While you can read lines using â€śfgets()â€ť, you need a way of telling when you have reached the end-of-file, so you wonâ€™t continue reading without any results. This is accomplished with the â€śfeof()â€ť functions, which returns â€śTRUEâ€ť or â€śFALSEâ€ť, weather the position of a file pointer is at the end of it. You now have enough information to read a file line by line:

```\$filename = "test.txt";
\$fp = fopen(\$filename, "r") or die("Couldnâ€™t open \$filename");
while(!feof(\$fp))
{
\$line = fgets(\$fp);
print "\$line";
}
fclose(\$fp);
```

While â€śfgets()â€ť works well around text files, you may sometimes want more functionality for your script. The â€śfread()â€ť functions returns the specified amount of data from a file, and doesnâ€™t take into consideration the end-of-line â€śnâ€ť, like â€śfgets()â€ť. â€śfread()â€ť also starts from the current file position, but if youâ€™re not happy with it, you can always change it using the â€śfseek()â€ť function.

```fseek(\$fp, 100); //moves the file pointer to the 100th byte
```

Any writing to a file is done with the use of â€śfwrite()â€ť or â€śfputs()â€ť functions, which both use a file pointer and a string to perform the writing:

```fwrite(\$fp, â€śHello from PHP!â€ť);

fputs(\$fp, â€śHello again from PHP!â€ť);
```

So far, these functions were great with a single user. However, on public web-sites, with many users accessing your scripts at the same time, your files could quickly become corrupt. PHP offers the â€śflock()â€ť function, which will lock a file and wonâ€™t allow other processes to write or read the file while the current process is running. â€śflock()â€ť requires a file pointer and an integer to do this:

```flock(\$fp1, 1); //shared lock â€“ allows read, doesnâ€™t allow write

flock(\$fp2, 2); //exclusive lock â€“ doesnâ€™t allow neither read, nor write

flock(\$fp3, 3); //release lock â€“ releases a shared or exclusive lock
```

There are a lot of other functions that you can use with files like: testing functions â€“ â€śfile_exists()â€ť, â€śis_file()â€ť, â€śis_dir()â€ť, â€śis_readable()â€ť, â€śis_writeable()â€ť, â€śis_executable()â€ť; functions that return information on files: â€śfilesize()â€ť, â€śfileatime()â€ť, â€śfilemtime()â€ť, â€śfilectime()â€ť. You can figure out what the function does by just reading its name; more information about them can be found in the PHP documentation.

## PHP Functions

### PHP Functions

A function is a block of code to perform a specific task. This block of code can be executed anywhere in the program by calling it’s name. A simple syntax of PHP function is:

```//define a function
function f_name()
{    block of code to perform a task;
}
//call a function
f_name();```

Let’s make a simple code to make our first PHP function.

```<html>
<body>
<?php
function first_func()
{   echo "This is my first PHP function.";
}
first_func();
?>
</body>
</html>```

We have made a function named, first_func. First, a function is created by using the keyword, “function” which is followed by the function name. The function name should be self explanatory so that it is easy to use in the program. A function name should start with an alphabet or an underscore and should not contain special characters except underscore. All the code of the function should be within a pair of curly braces. The function once created can be used anywhere in the program by just mentioning the name of the function. In the above example, we have called the function, “first_func” in the program after creating it. Let’s see the output:

`This is my first PHP function.`

When a function is created, the code within it is not executed. The function is merely created. The code within the function will be executed only when it is called.

#### Adding parameters in PHP function

In the example above, there are empty brackets after the name of the function. These brackets are empty because we have not used any parameters in it. Parameters can be used along with a function when a variable has different values in the program. Let’s see with the help of an example how parameters are used in a PHP function.

```<?php
{    \$sum=\$x+\$y;
echo "The addition of \$x and \$y is \$sum.";
}
?>```

In the above example, we have called the function, “add” twice. The result will be:

```The addition of 4 and 2 using add function:
The addition of 4 and 2 is 6.
The addition of 8 and 5 is 13.```

#### Return values in a PHP function

Till now we have seen that we call a function and it executes the code within it. But suppose that the output of the function has to be used outside the function. In this case, the function returns a value. Let’s see this with an example.

```<?php
{    \$sum=\$x+\$y;
return \$sum;
}
?>```

The output will be:

```The addition of 4 and 2 using add function:
6
13```

## PHP Loop

### PHP Loop

PHP loops are used to execute some code again and again for some definite number of times. There are many types of looping statements in PHP. They are:

• while loop
• do…while loop
• for loop
• foreach loop

Let’s discuss each of these loops.

#### While loop

The while loop is used to execute the specified code as long as the condition is true. The syntax of the while loop is given below:

```while (condition)
code to be executed;```

Let’s see a simple code to display numbers 1-10 by using while loop.

```<?php
\$i=1;
while (i<=10)
{     echo \$i."<br/>";
\$i++;
}
?>```

This simple code displays the numbers 1-10 in separate lines.

```1
2
3
4
5
6
7
8
9
10```

Let’s see how the above code is executed.
First the value of “i” is initialised to 1. Then the condition is checked and since “i” is less than 10, the code within the while loop is executed and 1 will be displayed. Then the value of “i” will be incremented. and the condition will be again checked and the new value of “i”, i.e. 2 will be displayed. This will continue till the condition is true. Notice, we increment the value of “i” in the loop. You should have a statement in your while loop which will eventually cause the condition to be false. If you don’t do this, the loop will never stop and your program will appear “frozen”.

#### Do…while loop

A do…while statement is a modified version of while loop. The main difference between both these loops is that the while loop checks the condition before executing the code within it while do while loop executes the code once and then checks the condition. Do while loop is used when the code withing the loop has to be executed at least once irrespective of the condition. The syntax of do while loop is:

```do
{    code to be executed;
}
while (condition);```

The following example will illustrate this:

```<?php
\$i=1;
do
{     echo \$i."<br/>";
\$i++;
}
while (\$i<=10);
?>```

The output will be:

```1
2
3
4
5
6
7
8
9
10```

In the example above, the parser will initialize the value of “i” to 1 and then it will execute the code within the do while loop and then it will check the condition. So even if the condition is false, the code within the loop will be executed at least once.

#### For loop

The for loop is one of the most used loops because it is very logical and easy to use. The syntax of the for loop is:

```for (initial; condition; increm)
{      code to be executed;
}```

The syntax of for loop has three parts:

• initial:Initialize the counter.
• condition:The condition to be checked at the beginning of each loop. If the condition is true the code within the loop will be executed and if it is false, it will not be executed.
• increm:Increment or decrement the counter.

Note that each part of the for loop is separated by semicolon. Below is a simple example:

```<?php
for (\$i=1; \$i<=10; \$i++)
echo \$i."<br/>";
?>```

and the output will be:

```1
2
3
4
5
6
7
8
9
10```

#### Foreach loop

The foreach statement is used to loop through arrays. For the current value of the array, the code within the loop is executed. The syntax of the foreach loop is:

```foreach (arrayname as value)
{      code to be executed;
}```

Let’s see a simple example:

```<?php
\$arr=array(1,2,3,4,5,6,7,8,9,10);
foreach (\$arr as \$v)
echo \$v."<br/>";
?>```

The output will be:

```1
2
3
4
5
6
7
8
9
10```

## PHP Arrays

### PHP Arrays

An array is a data structure that stores one or more values in a single variable. Each element in the array has its own id. There are 3 types of arrays in PHP namely,:

• Numeric Array: An array with a numeric ID key.
• Associative Array: An array where each ID key is associated with a value.
• Multidimensional Array: An array containing one or more arrays.

Let’s see each of these arrays.

#### Numeric array

Whenever some data is stored in an array, some ID is assigned to each value. In numeric array, the ID assigned to each value is numeric. Numeric arrays can be created in many ways. Let’s see those ways.

```//  Method I
\$name = array('Value1','Value2','Value3' );
//  Method II
\$name[] = 'Value1';
\$name[] = 'Value2';
\$name[] = 'Value3';
//  Method III
\$name[0] = 'Value1';
\$name[1] = 'Value2';
\$name[2] = 'Value3';```

Let’s see each of these ways.

```&lt;?php
//  Method I
\$name = array( 'Mike','Scott','Peter' );
echo \$name[0].", ".\$name[1].", ".\$name[2];
?&gt;```

In the first method, the keys are assigned automatically but remember that the keys start from 0 and not from 1.

```<?php
//  Method II
\$name[] = 'Mike';
\$name[] = 'Scott';
\$name[] = 'Peter';
echo \$name[0].", ".\$name[1].", ".\$name[2];
?>```

In the second method too, the keys are assigned automatically and the keys start from 0.

```<?php
//  Method III
\$name[0] = 'Mike';
\$name[1] = 'Scott';
\$name[2] = 'Peter';
echo \$name[0].", ".\$name[1].", ".\$name[2];
?>```

In the last and the third method, we have assigned the keys ourselves. The output of all the three methods will be the same as given below:

`Mike, Scott, Peter`

Below is an example to make arrays more clear:

```<?php
echo "looping through array";
\$x = array(0,1,4,9,16,25,36,49,64,81);
for(\$j = 0;\$j<10; \$j++)
{
echo " \$j  : \$x[\$j]";
}
?>```

and the output will be:

```looping through array
0
1
4
9
16
25
36
49
64
81```

#### Associative Array

In associative array, the ID key is associated with a value. There are two ways of creating an associative array.

```//  Method I
\$name = array("key1"=>Value1, "key2"=>Value2, "key3"=>Value3);
//  Method II
\$name['key1'] = "Value1";
\$name['key2'] = "Value2";
\$name['key3'] = "Value3";```

Let’s see both these methods.

```<?php
\$mdays = array("January" => 31,
"February" => 28,
"March" => 31,
"April" => 30,
"May" => 31,
"June" => 30,
"July" => 31,
"August" => 31,
"September" => 30,
"October" => 31,
"November" => 30,
"December" => 31
);
echo "February has ".\$mdays['February']." days.";
?>```

Now let’s see the second method.

```<?php
\$mdays['January'] = "31";
\$mdays['February'] = "28";
\$mdays['March'] = "31";
\$mdays['April'] = "30";
\$mdays['May'] = "31";
\$mdays['June'] = "30";
\$mdays['July'] = "31";
\$mdays['August'] = "31";
\$mdays['September'] = "30";
\$mdays['October'] = "31";
\$mdays['November'] = "30";
\$mdays['December'] = "31";
echo "February has ".\$mdays['February']." days.";
?>```

The output of both the methods will be:

`February has 28 days.`

#### Multidimensional Array

In a multidimensional array each element in the main array can also be an array. A simple multidimensional array is normally visualised as a matrix. Let’s see the syntax to create a simple multidimensional array.

```\$name = array
(
"array1" => array
(
"value1",
"value2",
"valuen"
),
"array2" => array
(
"value1",
"valuem
),
"arrayz" => array
(
"value1",
"valuey"
)
);```

Below is an example to make multidimensional arrays more clear:

```<?php
\$cds = array
(     "Christina Aguilera" => array
(
"Impossible",
"Beautiful",
"Dirrty"
),
"Kelly Rowland" => array
(
"Stole",
"Obsession"
)
);
?>```

To access the first cd of “Christina Aguilera”, the PHP script will be:

```<?php
echo "First cd of Christina Aguilera is ".\$cds['Christina Aguilera'][0];
?>```

and the output will be:

`First cd of Christina Aguilera is Impossible`

## PHP Switch

### Switch statement

The “switch” statement is similar to a series of “If…else” statements. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. The syntax of the “switch” statement will be:

```<?php
switch (expression)
{
case value1:
{ code executed if the expression has value1;
break; }
case value2:
{ code executed if the expression has value2;
break; }
default:
code executed if none of the value is true;
}
?>```

Let’s discuss the above syntax step by step. Let’s consider the simple script given below using the if, elseif, else statements.

```<?php
if (\$i == 0)
echo "i equals 0";
elseif (\$i == 1)
echo "i equals 1";
elseif (\$i == 2)
echo "i equals 2";
?>```

Now we will use the switch statement for the above task. First we will use only the “switch” statement and see what happens.

```<?php
switch (\$i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2"; }
?>```

Now, let’s see what the output will be. Suppose, the value of “i” is 1. The output will be:

```i equals 1
i equals 2```

which is certainly not the desired one. The switch statement is always used along with break. When the expression value matches any case value, it performs the code associated with it and when it encounters break statement, it comes out of the switch loop. If the break statement is missing, the pointer will perform all the statements subsequent to the matching case statement. In our example above, the value of “i” was 1. So the code underneath it was performed but since it did not encounter any break statement, the code beneath the subsequent case statement was also performed. So the correct script will be:

```<?php
switch(\$i) {
case 0:
{ echo "i equals 0";
break; }
case 1:
{ echo "i equals 1";
break; }
case 2:
{ echo "i equals 2";
break; }
}
?>```

The output of the above code will be what we desired, i.e.

`i equals 1`

If you look at the logic of the above program, there is no need to use break in the last case because the pointer will come out of the loop anyways. So, you can avoid using break statement in your last case. But if you have any confusion then use break in every case.

Now there’s only one thing remaining to be understood in the above syntax — “default”. The default case is similar to the else statement. The code in the default case is executed when the expression does not match any of the case values. The following example will make this clear.

```<?php
switch(\$i) {
case 0:
{ echo "i equals 0";
break; }
case 1:
{ echo "i equals 1";
break; }
case 2:
{ echo "i equals 2";
break; }
default:
{ echo "i does not equal any value";
break; }
}
?>```

If the value of i is 5, the output will be:

`i does not equal any value`

A point to remember:The default case should always appear as the last case in the switch statement.

## PHP if else

### If, If…else, elseif

Sometimes we want different actions to be performed for different actions. If, If…Else, and Elseif statements can be used for this purpose. Let’s have a look at each of these statements.

#### If statement

The most important is the “if” statement. It performs some actions if the specified condition is true. If the condition is not true, then the action will be ignored. The syntax of this statement is as follows:

```if (condition)
code to be executed if the condition is true;```

Let’s see an example.

```<html>
<body>
<?php
\$str="PHP";
if (\$str=="PHP")
echo "Condition is true.";
?>
</body>
</html>```

Let’s see what the output of the above script will be.

`Condition is true.`

The value of str is “PHP”. Hence, we get the above output because the condition is true. If the condition had been false, there would have been no output. Consider the script given below:

```<html>
<body>
<?php
\$str="Learn PHP";
if (\$str=="PHP")
echo "Condition is true.";
?>
</body>
</html>```

We will not get any output here because our condition is false. If the action to be performed has more than one statement, all the statements should be enclosed within a pair of curly brackets. Look at the code given below:

```<?php
\$str="PHP";
if (\$str=="PHP")
{ echo "Condition is true.";
echo "This will help to understand PHP better.";
}
?>```

The output will be:

`Condition is true.This will help to understand PHP better.`

#### If…else

The “if…else” statement provides an additional advantage. If provides the actions to be performed when the condition is true and when it is false. Let’s look at the syntax:

```if (condition)
code to be executed if the condition is true;
else
code to be executed if the condition is false;```

Have a look at the following example:

```<?php
\$city = "NJC";
if (\$city == "NYC")
{
echo "Condition is true.";
echo "I love NYC!";
}
else
{
echo "Condition is false.";
echo "I don't belong to NYC!";
}
?>```

Since our condition is false, both the statements after else will be executed. Hence, the output will be:

`Condition is false.I don't belong to NYC!`

#### Elseif

The “elseif” statement helps us to check more than one conditions. First look at the syntax and then we will see how it works.

```if (condition1)
{
code executed if condition1 is true;
}
elseif (condition2)
{
code executed if condition2 is true;
}
else
{
code executed if none of the conditions is true;
}```

Following example will make it more clear.

```<html>
<body>
<?php
\$city = "LA";
if (\$city == "NYC")
{
echo "I love NYC!";
}
elseif (\$city == "LA")
{
echo "I love LA!";
}
else
{
echo "My city is not there!";
}
?>
</body>
</html>```

The value of city is “LA”, hence, the output will be:

`I love LA!`

The “elseif” statement allows us to check multiple conditions. There can be multiple elseif statements.