The PERL (Almost Weekly) Manual: The 2nd Issue ---By Ankit Fadia [email protected]

http://blacksun.box.sk

_____________________________________________________________________________

Welcome to the second issue of The PERL (Almost Weekly) Manual. In the first issue I had given a general introduction to Perl and had covered basic Perl Topics.This Issue too concerns with nothing too Advanced but covers some Basic Perl things.This can be said to be a continuation of the first issue.Once you have a Sound Perl base, then it would become easier for you guys to understand the advanced important topics which will allow you to make some very useful programs.So I do suggest that you read these issues very carefully, so that you do not have any problems while reading the advanced topics.

Loops

Loops are very useful when you need to execute the same chunk of code or the same command over and over again. Say for example you want to print your name on the screen 5 times.You can do it by the following snippet of code:

$scalarvar= 'Ankit\n' ;

print '$scalarvar' ;

print '$scalarvar' ;

print '$scalarvar' ;

print '$scalarvar' ;

print '$scalarvar' ;

The Above program will print Ankit on the screen five times(Each Ankit in a new line.), it will produce the desired result but the above code is really cumbersone and is not really efficient. Perl has many looping statements like the For-Next loop, the while loop and also the do while loop, which allow one to repeat a set of statements within the body of the loop to be repeated as long as a condition is being fulfilled.The above may sound a bit weird but read on and things will definitely become clearer.


The While Loop

Lets first go through the basic Syntax of the While loop

while (Condition) { Body }

This means that as long as the condition is true, the commands within the curly brackets i.e. the body of the while statement are executed. So now the earlier printing program can be rewritten as:

$count='1';

while ($count <= 5) {

print 'Ankit\n' ;

$count++ ;

}

The while loop not only can be used to repeat a code snippet, it allows us to validate the user input and perform a certain pre defined task accouring to the result of the validation.This will become clearer after we consider the following scenario: Say you want to make a Perl Script which asks the user to enter the username and if and only if the username entered by the user is 'root' then display the system info. So to do the above we write the following script:

print 'Username:' ;

$user= <>;

chomp $user;

while ( $user eq "root" ) {

print "System Ingo goes here:";

}

Output:

Username:ankit

Now as I entered ankit as the UserName the condition was not fulfilled and the body of the while statement was not executed.So lets see what happens if we type root as the Username.

Output:


Username:root

System Ingo goes here:System Ingo goes here:System Ingo goe

es here:System Ingo goes here:System Ingo goes here:System

Ingo goes here:System Ingo goes here:System Ingo goes here

e:System Ingo goes here:System Ingo goes here:System Ingo g

goes here:System Ingo goes here:System Ingo goes here:Syste

em Ingo goes here:System Ingo goes here:System Ingo goes he

ere:System Ingo goes here:System Ingo goes here:System Ingo

o goes here:System Ingo goes here:System Ingo goes here:Sys

stem Ingo goes here:System Ingo goes here:System Ingo goes

here:System Ingo goes here:System Ingo goes here:System In

ngo goes here:System Ingo goes here:System Ingo goes here:S

System Ingo goes here:System Ingo goes here:System Ingo goe

es here:System Ingo goes here:System Ingo goes here:System

Ingo goes here:System Ingo goes here:System Ingo goes here

e:System Ingo goes here:System Ingo goes here:System Ingo g

goes here:System Ingo goes here:System Ingo goes here:Syste

em Ingo goes here:System Ingo goes here:System Ingo goes he

ere:System Ingo goes here:System Ingo goes here:System Ingo

o goes here:System Ingo goes here:System Ingo goes here:Sys

stem Ingo goes here:System Ingo goes here:System Ingo goes ^C

Now what did happen here? Well when the Perl program asked for the Username, I entered root, so the scalar $user has the value root. Then the perl Interprator reaches the while statement and the condition evaluates to true, the body of the while statement is executed and the messages System Ingo goes here: is displayed once. After the message is printed, once the condition is evaluated again and as it once again evalutes to true as the scalar $user has the same value i.e. root and hence the body is executed once again. Thus like this the loop continues as the condition is always true and hence it becomes an infinte loop.

Note: To get out of an infinite loop type CTRL + C.

So while writing the while statement you need to keep in mind that the loop does not become an infinte one. So in order to print the message just once in the above example the Perl code will change to:

print 'Username:' ;

$user= <>;

chomp $user;

while ( $user eq "root" ) {

print "System Ingo goes here:";

$user=' Xyx';

}

So now once the message is printed once, the value of the scalar $user is changed and then when the codition is evaluated, as the value of $user is Xyz the codition is not fulfilled and hence the Body of the While Statement is not executed.

The For Loop

Basic Syntax of the For Loop would be:

for (START; STOP ; ACTION) { Body }

The above statement initialluy executes the START statement and then repeatedly executes the BODY statement as long as the STOP statement remains true. The ACTION statement is executed after every iteration.

All this will become clearer after the following example:

In this example we want to print all the alphabets from a to z.

for($letter= 'a' ; $letter lt 'z' ; $letter++) {

print $letter;

}

Explanation: First of the the for statement assigns the scalar $letter the value 'a' and then check if the scalar $letter is less than 'z' and if this is true then it executes the Body of the FOR statement i.e. it prints the value of $letter. Once the value of $letter has been printed on the screen, the value of $letter is increased by 1 i.e. the Action is executed.

The syntax of the FOR statement is same as that used in other programming languages like C, C++ and JavaScript etc.

Arrays

You already know the first kind of Data Type, scalars. Although they are quite useful, they also have a dark side too, a single scalar can store only a single value, so in order to store 100 values we would have to have 100 scalars , which would make our programs very cumbersome, difficult to debug and difficult to understand and also difficult to manage. The answer to this problem is the use of Arrays which are a collection of related scalar values glued together. As the scalar variables begin with the $ sign, the Array variables begin with the @ sign. Thus any variable with a preceeding @ sign is an Array and any variable with the $sign is a scalar variable.

Lets take an example of an array:

@strings=('ankit', 'ankit2', ankit3');

is an array of strings and has 3 elements.

@nums=('34', '45', '65');

is an array of numbers and has 3 elements.

In Perl unlike in C an array can have mixed data types, i.e. it can contain both Numbers and strings.For example,

@mixed=('23','54','Ankit','52');

is a mixed array and has 4 elements.

Individual elemts of an array can be referred to my using the following syntax:

$newvar=$array1[x];

The above statement assings the scalar $newvar the value contained by the x'th element of the array, 'array1'. Note that to refer to individual elements of an array we use the $ sign instead of the @ sign.

Another thing to remember would be the fact that an array starts counting from zero, from that what I mean is that the first element of an array is referred to as the o'th element.The above will become clearer after the following examples:

@array1=('I am first', 'I am second' , 'I am third', 'I am fourth');

$var1=$array1[0];

$var2=$array1[1];

$var3=$array1[2];

$var4=$array1[3];

print $var1;

print $var2;

print $var3;

print $var4;

OutPut:

I am firstI am secondI am thirdI am fourth

This means that the o'th element is the first element in the array and the 1'th element is the 2'nd element in the array of values.

For Example,

@mixed=('23','54','Ankit','52');

is a mixed array and has 4 elements

Now the above mixed array contains 4 values, but Perl starts counting from 0, this means that $mixed[0] is 23 and $mixed[1] is 54 and $mixed[2] is Ankit and so on.

NOTE: In $array[n], the n is known as the indice.


In Perl the indices can also be negative. For example,

$array[-2];

is the 2nd last element

$array[-1];

is the last element

THE FOR EACH LOOP: Moving through an array

In the above section, I had given an example in which we print various elements of an array by writing multiple print statements.That again is quite cumbersome and use of the For-Each loop makes your Perl programs easier to use i.e more efficient.

The Basic Syntax of the For Each Loop would be the following:

foreach SCALAR (ARRAY) { BODY }

The above statement executes the commands in the BODY once for every ARRAY element. The current array element is placed in SCALAR.

Lets take the following example in which we need to move through the entire array and print all it's values.

@os = ('Windows', 'Linux' , 'MacOS' , 'BeOS');

print 'Now Printing known Operating Systems:' ;

foreach $os(@os) {

print $os;

}

Output:

Now Printing known Operating Systems:WindowsLinuxMacOSBeOS

The for each loop is pretty self explanatory and is very useful for going through the contents of an array and printing them.

Functions Associated with Arrays

Perl comes with many in built functions that allow us to manipulate data in an array.

push( ) and pop( )

push( ARRAY, LIST) appends the LIST of data values to the end of an array.

This means that for example,

@array1=('123','456');

push( @array1, 789);

print $array1[-1];

prints 789 on the screen and

@array1=('123','456');

push( @array1, 789,abc);

print $array1[-1];

prints abc on the screen.

pop(ARRAY) removes and returns the last element of the ARRAY.

As strings have the function chop(), arrays have the pop() function.

unshift( ) and shift( )

unshift( ARRAY, LIST) appends the LIST of elements to the beginning of the ARRAY.

It can be said to be the opposite of push( ).

shift( ARRAY) removes and returns the first element of the Array.

It can be said to be the opposite of pop( ).

splice( )

The basic syntax of this function would be:

splice(ARRAY,OFFSET,LENGTH,LIST) removes and returns LENGTH elements of ARRAY starting from OFFSET replacing them with LIST.

For example,

@array1=('1','2','3','4');

print @array1;

splice(@array1,2,2,a,a);

print @array1;

Output:

123412aa

The LENGTH and LIST arguments can be removed.The following examples make it more clear:

splice(@array1,2);

removes and returns all elements after 2 including 2.

splice(@array1, 2, 2);

removes and returns $array1[2] and $array1[3].

Default Variables

Perl is full of default variables, that one does not even have to define and are automatically defined by Perl and assigned a value.Well lets move on to the first of those.

$_

"The Programmer said that the programmer will start programming as soon as the programmer gets the Perl Editor"

Read the above sentence and then read the below sentence:

"The Programmer said that he will start programming as soon as he gets the Perl Editor"

In the second sentect pronouns like he replaced the nouns and made the sentence better.

Perl too unlike other programming languages has a default variable '$_' which solves the above problem.Lets take the example of the FOR EACH loop to undertand more about the $_ variable.

Normally you would write something like the following:

foreach $array(@array) { print $array; }

Now with the use of the Default Variable $_ the above code will condense to:

foreach(@array){print;}

So what exactly happened? Well when the loop has no scalar before it, it uses the deafult variable $_ instead and the print function if not given any argument prints the value contained by $_.

Thus as a result,

print($_); and print; are the same and

chomp($_); and chomp; are the same.

Well that wraps up this week's Perl Journal. Next Week's issue is going to be on I\O and I will be discussing files and other I\O.

Ankit Fadia

[email protected]

To receive more tutorials on Hacking,Cracking, Perl, C++ and Viruses/Trojans and lottsa more join my mailing list:

Send an email to [email protected] to join it.

Visit my Site to view all tutorials written by me at: http://www.crosswinds.net/~hackingtruths