What's New!

Chat with
Hackers

How to Defend
Your Computer 

The Guides
to (mostly) 
Harmless Hacking

Happy Hacker 
Digests (old stuff) 

Hacker Links 

Hacker
Wargames 

Meet the 
Happy Hacksters 

Help for 
Beginners 

Hacker 
Bookstore 

Humor 

It Sucks 
to Be Me!

How to Commit
Computer Crime (not)! 

What Is a 
Hacker, Anyhow? 

Have a 
Great Life! 

News from the 
Hacker War Front

New Digest series: Programmers' Edition

Want to learn insanely fun, yet easy things to do with programming?
You aren't a REAL hacker until you have learned to program. We are already learning Perl for Unix systems from Mike Miller's Perl 101, but, heck, you can never be too rich, too thin (if you're a woman) or learn too much programming. So with Ankit Fadia's new programmers' guide, you can learn hacker-style programming on Windows, too.

Ankit Fadia has written many mostly harmless hacking tutorials (see
his Hacking Truths http://hackingtruths.tripod.com). We've posted
one of his best at our web site (http://happyhacker.org/ht/secrets.shtml). It tells you how to totally remake your Windows system with things far more amazing than just changing your bootup and shutdown screens. We plan to get his entire archive online at our site soon. -- Carolyn Meinel
__ __ __ __ __
/ // /__ ____ ___ __ __ / // /__ _____/ /_________
/ _ / _ `/ _ \/ _ \/ // / / _ / _ `/ __/ '_/ -_)__/
/_//_/\_,_/ .__/ .__/\_, / /_//_/\_,_/\__/_/\_\\__/_/
/_/ /_/ /___/

___ _ __
/ _ \(_)__ ____ ___ / /_
/ // / / _ `/ -_|_-</ __/
/____/_/\_, /\__/___/\__/
/___/

June 3rd, 2000

Before I go ahead with the first Programming Digest, I think some
self introduction is needed. I am Ankit Fadia who is editor of the
new Happy Hacker Digest: The Programming Digest, in which I will be writing Tutorials on C, Perl, some Web Programming stuff and also sometimes information on Assembly. I am a teenager from India and ama freelance Web Designer. Although I would prefer if you would contact me at programmers@cmeinel.com , you can also contact me at my personal email address: ankit@bol.net.in

You cannot become a good hacker unless you have some programming knowledge. Not only for Hacking, Perl is very much useful for developing security related and also normal but useful programs. In this manual, I will be starting from the basics of Perl and then will move on to some cool advanced stuff. I am assuming that you do not have any previous programming experience, although a sound background in C, Basic or JavaScript will help you tremendously.

Perl : The Basics

Perl was born in 1987 and was developed by Larry Wall by fusing the Unix utility awk with a system administration tool he had developed. Perl's development has been done on the lines of including all the useful and important aspects of other programming languages and removes the not so useful aspects. Now Perl is an interpreted language, that means that the Perl code is run as it is and it is not complied like other languages. When you first run a Perl program, it is first compiled into a bytecode, which is then converted into machine instructions.

Now first of all, before you can start writing your own Perl
programs, you need ActivePerl ,the Perl Interpreter. You can
download ActivePerl for Win32 from: http://www.activestate.com/

Follow the links for the latest build and download it. It is around a
5MB download. After installing ActivePerl ensure that the file
perl.exe is in your path statement. Although ActivePerl Build 509
sets
the path automatically during setup, just make sure that your path
statement contains reference to the file perl.exe by typing "set" at
the command prompt(without quotes). Now look for the "PATH"
environment variable and make sure that it contains the line
"c:\perl\bin" in that statement. Normally it would contain this line,
but if it doesn't then open the file c:\autoexec.bat in Notepad and
add the following line:

PATH=%PATH%;.;c:\perl\bin

Now save the file and reboot or update the environment for that
session by running the file autoexec.bat by going to DOS and typing
autoexec.bat

Note: NT users will just have to update the current system
environment by going to Control Panel System

Now let's start by the obligatory Hello World Program. Now to write Perl programs you do not need any special Perl Text Editor, notepad would do just fine. So launch Notepad and type the following:

Print "Hello World\n"; #This prints Hello World on the Screen

Now save the file by the name "first.pl". You can replace first by
any name of your choice but just remember that the file should have a .pl extension. Now go the DOS Prompt and then to the folder in which you had saved the above file and type:

C:\myfilesfirst.pl

Note: Replace filename with the name of the file that you chose while saving.

If the above program does not work that is you get an error, then
check your path statement or try to write perl filename.pl instead of
just filename.pl

Now lets analyze the program, the word print calls the print function
which takes the text from within the quotes and displays it on the
screen. The "\n" symbolizes a new line or the carriage return. Almost all lines in Perl end with a semicolon.

Scalars

Now let's make the above program a bit more complex by introducing a scalar.

$scalarvar= 'Hello World\n' ; #the Variable $scalarvar has the
value Hello World\n
print "$scalarvar" ; #Prints value of Variable
$scalarvar

Now scalars are declared by the $ sign followed by the Variable name. The first line feeds the text with the quotes into the scalar whose name is scalarvar. We know the $scalarvar is a scalar because it is preceded by the $ sign.

Now you must be wondering why I have used single quotes in the first line and double in the second. Now the reason behind this is the fact that Perl performs variable interpolation within double quotes this means that it replaces the variable name with the value of the
variable. This will become more understandable with the following
examples,

$scalarvar= 'Hello\n' ; # Variable $scalarvar has the value Hello\n
print '$scalarvar' ; # But as we use single quotes there is no
variable interpolation and function print prints $scalarvar on the screen.

Output will be:

$scalarvar

The following is an example of Variable Interpolation:

$scalarvar= 'Hello' ;
print "$scalarvar" ; # In this case Variable Interpolation takes
place the Print function is fed the value of the variable
$scalarvar.

Output will be:

Hello

By now the difference between single quotes and double quotes would have become quite clear.

Interacting with User by getting Input

The Diamond Operator i.e. <> is the Perl equivalent of the C function scanf and the C++ function cin. It basically grabs input from the user to make a program interactive. It will become more clearer after the following example:

print 'Enter your Name:' ;
$username= <> ; #The User will enter a text which will be fed into
the scalar
print 'Hi $username' ;

Output will be:

Enter your Name: Ankit
Hi Ankit

This program will print the text Enter your Name: on the screen and
will wait for user input. The text entered by the user will be fed
into the scalar $username. Then the program will print Hi followed by the text entered by the User.

chomp( ) and chop( )

Now sometimes you need to manipulate strings and do this there are many functions available which can be used. So when do you need to use chop( ) and chomp( ) Consider the following situation……You need to write a program to print the name and age of the user which would be input by the User itself. Now consider the following code…

print "Enter your name:" ;
$name=<>;
print "Enter your age:" ;
$age=<>;
print "$name";
print "$age";

Output will be:
Enter your name :Ankit
Enter your age:14
Ankit
14

Now what happened here? Why did Perl print Ankit and 14 in different lines? There was no new line i.e. "\n" character in this program. Now what actually happened lies in the fact that when the user is given the Input prompt that is when the user is needed to enter some input, Perl keeps on accepting input from the user as long as the user provides the ending operator.(The ending operator is Carriage Return or Enter).

When the ending operator is provided by the user then Perl stops
taking input and assigns the data input by the user to the variable
specified including the Carriage Return. This means that in the above program the value of the scalar $name is Ankit followed by carriage return which is equivalent to "Ankit\n". So when we print the scalar $name then the value of $name is printed followed by carriage return or "\n".

To avoid this problem we use chop( ) and chomp( ).

The basic difference between these two functions will become clearer with the below example:

$var1="Ankit";
chop($var1);
print $var1;

The Output will be:
Anki

In the below example:

$var1="Ankit";
chomp($var1);
print $var1;

The Output will be:
Ankit

Now the difference between chop( ) and chomp( ) is that chop( ) will remove the last character of the string irrespective of the fact,
what it is. While chomp( ) will remove the last character if and only if the last character is "/n".
This means that

$var1="Ankit\n";
chomp($var1);
print $var1;

and

$var1="Ankit\n";
chomp($var1);
print $var1;

will have the same effect as the last character here is "\n". So our
problem of printing both the name and age of the user on the same
line can be solved by the following snippet of code:

print "Enter your name:" ;
$name=<> ;
chomp($name);
print "Enter your age:" ;
$age=<> ;
chomp($age);
print "$name";
print "$age";

Output now would be:

Enter your name: Ankit
Enter your age:14
Ankit14

Operators

Perl too has the same basic operators found in other programming
languages but it does have some additional operators too.

Binary Arithematic Operators

op1+op2 Addition
op1-op2 Subtraction
op1*op2 Multiplication
op1/op2 Division
op1 % op2 Modulus

The Exponentiation Operator (**)

This is the raise to the power of operator,
For Example:

$var= 5;
$var1= $var ** 3;
print $var1 ;

Output will be:
125

The Unary Arithmetic Operators

+op and -op are used to change the sign of the operator. For example:
$var=4;
$var1= -4;
print var1;

Output will be:
-4

++op and --op are used to increase or decrease the value of the
variable value before usage and op++ and op-- are used to increase or decrease the value of the variable after usage. Consider the
following examples:

$var=4;
print ++$var;
This will print:
5
$var=4 ;
print $var++;

This will print 4 on the screen and the value of $var will become 5
after printing 4 on the screen.

$letter="a";
$letter++
Now $letter is b

$letters="xz";
$letters++;
Now $letters is ya

Other General Operators

The Concatenation Operator ( . )
$var="Hack" ;
$var = $var . 's';

Now $var become Hacks instead of Hack.
The " x" operator
$var = "ab" x 4;
print $var;
Will print abababab

Conditional Statements

First of all understand the difference between = and ==

Now the = operator assigns the variable on the left with the value on the right. "= = is used to assign variable their values and the ==
operator compares and checks if the value on the left is equal to the
value on the right and is used in the IF THEN ELSE statement.

Now Perl includes the following logical operators:

X >Y This is true if the value of x is greater than y
X < Y This is true if the value of y is greater than x
X <= Y This is true if X is equal to or smaller than y
X = Y This is true if X is equal to or greater than y

The above operators are for numbers and for strings the following
operators are used:

eq Is the alphanumerical equivalent to == and tests for strings
whereas == tests for numbers
x lt y Is true if the string x comes before string y in alphabetical
order.
x gt y Is true if the string x comes after string y in alphabetical
order.
x le y Is true if the string x comes before or is equal to string y.
x ge y Is true if the string x comes after or is equal to string y.

Now that you know the Logical operators lets move on the IF THEN statement. The basic syntax of an If then statement is:

if ( Condition ) { Body } executes body if condition evaluates to
true.

IF you have understood the logical operator and the basic syntax then forming a conditional If Then statement is pretty simple. Anyway I would be providing one or two examples.

print" Enter your name:";
$name=<> ;
chomp $name ;
if ( $name eq 'Ankit') {
print "Hi Ankit";
}

This prints HI Ankit if the User's name is Ankit. Now lets make
things a bit more interesting by inserting the else clause into the IF THEN statement and turning it into an IF THEN ELSE statement, then the above example would become:

print" Enter your name:";
$name=<> ;
chomp $name ;
if ( $name eq 'Ankit') {
print "Hi Ankit";
}
else {
print " You are not authorised to use this PC" ;
}
If the name input by the user is something other than Ankit then Perl
executes the else statement and if the name input by the user is
Ankit then it will execute the then statement i.e. the command after the first {.

Assignment Operators

$var .= 's' is equivalent to $var = $var . 's'
$var x= 7 is equivalent to $var = $var x 7
$var += 7 is equivalent to $var = $var + 7
$var -= 7 is equivalent to $var = $var - 7
$var *= 7 is equivalent to $var = $var * 7
$var /= 7 is equivalent to $var = $var / 7

The ?: Operator

This is pretty much similar to the IF then Else Statement but is just
its shorthand.
For example;
$var=( $num == "5") ? "Ankit" : "End" ;
The Variable $var is assigned the value Ankit if $num== 5 else $var
is
assigned the value End

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 cumbersome 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

Let us 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 according 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
let us 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 Interpreter 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 evaluates 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 infinite 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 infinite 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 condition is evaluated, as the value of
$user is Xyz the condition 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 initially 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 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
Scalars 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 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 preceding @ sign is an Array and any
variable with the $sign is a scalar variable.
Let us 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 elements of an array can be referred to my using the
following syntax:

$newvar=$array1[x];

The above statement assigns 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 0'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, let's 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 sentence 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 understand 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 default 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.

@ARGV

Till now we have learnt about only one special Variable, the $_
variable. Another useful variable is the @ARGV variable which
contains a set of elements of all command line arguments provided to the Perl Program. The first command line argument can be found at $ARGV[0], the second at $ARGV[1] and so on. Let's suppose a Perl Program was called using three command line arguments, which are Ankit, Fadia, Anki123. Then @ARGV would contain Ankit, Fadia and Anki123, with $ARGV[0]=Ankit, $ARGV[1]= Fadia and $ARGV[2]= Anki123.
For Example,

The following PERL program takes the number which was passed as a command line argument, then multiplies this argument with 4 and finally displays the result on the screen.

$number = $ARGV[0];
print $number *4;

Output:

C:\perl>perl filename.pl 5
20

Not all functions assume $_ to be the default variable, some
functions take @ARGV instead. For Example, the shift( ) function.
What the shift( ) function does is remove and return the leftmost or the first argument of @ARGV. To understand the use of the shift( )
function, consider the following example.

In this PERL program ,we assume that the User Passes two arguments, the Program then takes the two arguments adds them and then displays the sum on the screen.

$first = shift;
$second = shift;
print $first + $second;

Output:

C:\perl>perl filename.pl 3 5
8

Well that's it for this week's manual, see you next time. Hope you
enjoyed this tutorial. The next manual is going to be probably on C.
This is a list devoted to *legal* hacking! If anyone plans to use any
information in this Digest or at our Web site to commit crime, go
away! We like to put computer criminals behind bars where they
belong!

Clown Princess Carolyn Meinel Happy Hacker is part of a 501 (c) (3) tax deductible
organization


Carolyn's most
popular book,
in 4th edition now!
For advanced
hacker studies,
read Carolyn's
Google Groups
Subscribe to Happy Hacker
Email:
Visit this group
Google Groups
Subscribe to Happy Hacker
Email:
Visit this group
 © 2013 Happy Hacker All rights reserved.