Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

Perl Part II

This document provides an introduction to using arrays in Perl programming. It discusses how to define and assign values to array variables, access individual elements, determine the length of an array, split strings into arrays using separators, remove trailing newline characters using chop, and compare strings. It also covers conditional statements like if/else and while loops. Key points include: 1) Array variables in Perl begin with @ and store lists of values that can be accessed by index like $array[0]; 2) The split function parses a string into an array using a separator like a space or comma; 3) chop removes the newline character from strings read from input; 4) String comparisons use operators like eq,
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Perl Part II

This document provides an introduction to using arrays in Perl programming. It discusses how to define and assign values to array variables, access individual elements, determine the length of an array, split strings into arrays using separators, remove trailing newline characters using chop, and compare strings. It also covers conditional statements like if/else and while loops. Key points include: 1) Array variables in Perl begin with @ and store lists of values that can be accessed by index like $array[0]; 2) The split function parses a string into an array using a separator like a space or comma; 3) chop removes the newline character from strings read from input; 4) String comparisons use operators like eq,
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 17

Introduction to Perl Programming II

Array Variables
Perl enables you to store lists in special variables designed for that purpose. These
variables are called array variables (or arrays for short).

For Example,

@array = (1, 2, 3, 4, 5);


(Here, the list (1,2,3,4,5) is assigned to the array variable @array.)

OR we could write this as @array = (1 .. 5);

(.. allows us specify a range of numbers,


e.g. 20..24 is the same as 20, 21, 22,23, 24.)

Note, the array variable’s name begins with @.

This distinguishes array variable names from scalar variable


names, which begin with $.

Another example

@people = (“John”, “Pat”, “Mary”);


(Here, the list (“John”, “Pat”, “Mary”) is assigned to the array variable
@people.)

You refer to any element of an array variable as a scalar variable.

The first element of the list @array is $array[0]

the second element of the list is $array[1] ……….

the last element of the list is $array[‘length of list’ -


1].
Examples

$x = $array[0];

(Here the first element of @array is assigned to the scalar


variable $x)
$array[2] = 5;

(Here the third element of the array variable @array is


assigned the number 5.)
Array Length
The length of a list assigned to an array variable can be
determined by assigning the array name to a scalar variable.
Example:

@array = (1,2,3);

$len = @array;
($len, now has the value 3, which is the length of the list
currently assigned to @array.)

This is used very frequently. For example we may read a line of


text from a file/standard input and break it into a list of words
which we then process one word at a time. Consequently, we
need to compute the number of words in the list.

Arrays & Strings


To parse a character string into separate items the library
function split is used.

(Note: The C library provides the strtok() function for similar


purposes)

2
The syntax for split is

@words = split( /separators/, string);

where
string is the character string to split

/separators/ specifies what separates the words in a string and

and words is the resulting array.

Example 1:

$string = “words::separated::by::colons”;

@words = split(/::/, $string);


The first argument passed to split tells it how to break the string
into separate parts.

In this example, the first argument is :: so split breaks the


string into four separate parts in this case. The result is then the
list

(“words”, “separated”, “by”, “colons”)

which is assigned to the array variable @words. Now


$words[1] is the string "separated".

Example 2:

$string = "Hello wild windy world ";


@list = split(/ /, $string);

Here the separator is the SPACE character. In this case split


breaks the string into four separate parts. The result is then the
array

3
("Hello", "wild", "windy", "world")

which is assigned to the array variable @list.

$list[0] is the string "Hello".


$list[1] is the string "wild".
$list[2] is the string "windy".
$list[3] is the string "world".

Example 3
#!/usr/bin/perl

print(“Enter some words separated by


commas”);
$line = <STDIN>;

@w = split( /,/, $line );

print(“First word”, $w[0]);


print(“Second word”, $w[1]);

Here the separator is a comma ','. This is a very common


separator, for example spreadsheets can be saved as CSV files
where CSV means Comma Separated Values.

The chop Library Function


This function assumes that a string is stored in the
variable passed to it; chop’s job is to delete the last
character in the string.

For Example,
$line = “This is my line”;
chop($line);

4
After chop is called, the value of $line becomes,
"This is my lin"
The chop function is used to remove the newline character from
strings read from <STDIN>. When a string is read from
<STDIN> the newline character is stored with the string.

If for example, you enter bill as a line of input, then “bill\n” is


read in (i.e. bill followed by the newline character).

When chop is applied to this string (i.e. “bill\n”) the newline


character is removed from the string and we are left with
“bill”.

Example,
$name = <STDIN>;

This reads a name, including the newline character into $name. We can
remove the newline character using chop:

chop($name);
It is a very common mistake for beginners to forget to
remove the trailing newline and as a result get a comparison
failure.

As described above, if we read the string "bill" from <STDIN>


what we actually read is "bill\n". If we then compare what we
have read i.e. "bill\n" with the string "bill" we find they do not
match.

The following example highlights the issue:

#!/usr/bin/perl
print("Enter your name: ") ;
$name = <STDIN>;
print("hello ", $name, " nice to meet
you!") ;

5
chop($name);
print("\n\nAfter the axeman!!\n") ;
print("hello", $name, " nice to meet you!\n")
;

Assume the user enters "bill", then the program outputs:


hello bill
nice to meet you

After the axeman!!


hello bill nice to meet you

The first time we print $name, it still contains the newline


character and so our output is split over two lines.

After using the chop function, the newline character has been
removed and the output is as expected on a single line.

String Comparison Operators

Comparison Operators

String operator Comparison Numeric operator


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 !=

When characters (or strings of characters) are compared, it is


their ASCII code that is used to determine the result. For
example, the string aaa is less than the string bbb, because the
ASCII code of 'a' is less than the ASCII code of 'b'.

Note that the ASCII codes of the uppercase letters are less than
the ASCII codes of the lowercase letters. This means for
example that the character 'Z' "is less than" the character 'a'.

6
The ASCII code for uppercase letters range from 65 ('A') to 90
('Z') and for lowercase from 97 ('a') to 122 ('z').

7
String comparison examples:

$result = “ZZZ” lt “aaa”; # result is true

$result = "aaa" lt "bbb"; # result is true

$result = "aaa" gt "bbb"; # result is false

$result = "aaa" eq "bbb"; # result is false

$result = "aaa" le "aaa"; # result is true

$result = "aaa" ge "bbb"; # result is false

$result = "aaa" ne "aaa"; # result is false

$result = "aaa" cmp "bbb"; # result is -1

String Concatenation
The string-concatenation operator, . , joins two strings together.

For Example,

$newstring = “potato”.”head”;

This assigns the string potatohead to $newstring.

8
Conditional Statements
The if Statement

The syntax for the if statement is similar to that of C except that


you MUST use {}:

if (expr)
{
statement_block
}
For example,

if ($number >0 )
{
print(“The number is not zero.\n”);
}
Another example,

if ($number == 21)
{
print(“The number is 21\n”);
}

A final example,

if ( $word eq “hello”)
{
print(“You entered hello.\n”);
}
Note we use eq to test for string equality.

The if - else Statement

9
The syntax for this statement is:

if (expr)
{
statement_block_1
}
else
{
statement_block_2
}

The following program reads in two numbers and displays a


message stating whether the two numbers are equal or not
equal.

#!/usr/bin/perl

print(“enter first number: ”);


$number1 = <STDIN>;
chop($number1);
print(“enter second number: ”);
$number2 = <STDIN>;
chop($number2);
if ($number1 == $number2)
{
print(“The two numbers are equal.\n”);
}
else
{
print(“The two numbers are not equal.\n”);
}

10
The if – elsif – else Statement
The syntax for this statement is:

if (expr_1)
{
statement_block_1
}
elsif (expr_2)
{
statement_block_2
}
elsif (expr_3)
{
statement_block_3
}
else
{
default_statement_block
}

11
The while loop
A while loop allows you repeat one or more Perl statements.
The syntax for the while loop is:

while ( expr )
{
statement_block
}
For example, the following program is an implementation of a
simple guessing game where the user is asked to guess the
"magic" word known only to the program:

#!/usr/bin/perl

$guess = " ";


$magic = "blue" ;

while ( $guess ne $magic )


{
print(“Guess the magic word: ”);
$guess = <STDIN>;
}
print("Well done – you guessed correctly \n");

The above program DOES NOT work – Why ?

When $guess is read, it contains a trailing newline which


must be removed before comparing it to the magic word
i.e. the line

chop $guess ;

should be inserted after reading the guess.

The last statement

12
Perl provides the last statement, (equivalent to break in
C, to allow you break out of a loop. For example, in the
guessing program above, the program will loop until the
user makes a correct guess i.e. potentially an endless
loop. The following version uses a last statement to
solve this problem and only allows 3 guesses:

#!/usr/bin/perl

$guess = " ";


$magic = "blue" ;
$numguess = 0;

while ( $guess ne $magic )


{
print(“Guess the magic word: ”);
$guess = <STDIN>;
chop ($guess) ;
$numguess++;
if ($numguess > 3)
{
last ;
}
}
if ( $numguess > 3 )
{
print("Sorry too many guesses \n");
}
else
{
print("Well done – you guessed correctly \n");
}
Perl also provides a next statement (equivalent to C's continue
statement) which allows you return to the loop test from inside
a loop body.

13
The until Statement
There is a slight difference between the while and the
until statement, namely,

- The while statement loops while its conditional


expression is true.
- The until statement loops until its conditional
expression is true (i.e. it loops as long as its conditional
expression is false).

The syntax for the until statement is:

until( expr )
{
statement_block
}
Example 1:

$count = 0 ;
until($count == 5)
{
print(“still in the until loop.\n”);
$count ++;
}
print(“$count is now 5.\n”);

14
Example 2:

The following program reads an attempt at calculating


'17+26'. The program then loops until the correct answer
is read in, namely 43.

#!/usr/bin/Perl

print(“What is 17 plus 26? \n”);


$correct_answer = 43;
$input_answer = <STDIN>;
chop($input_answer);
until($input_answer == $correct_answer)
{
print(“Wrong. Keep trying. \n”);
$input_answer = <STDIN>;
chop($input_answer);
}
print(“You got it. \n”);

15
The for Statement
The syntax of the for statement is similar to that of C:

for (expr1; expr2; expr3)


{
statement_block
}

- expr1 is the loop initialiser. It is evaluated only


once, before the start of the loop.

- expr2 is the conditional expression that


terminates the loop. The conditional expression in
expr2 behaves just like the ones in while and if
statements. If its value is 0 (false), the loop is
terminated, and if its value is nonzero, the loop is
executed.

- statement_block is the collection of statements


that is executed if (and when) expr2 has a nonzero
value.

- expr3 is executed once per iteration of the loop


and is executed after the last statement in
statement_block is executed.

16
Example 1:

The following program prints the numbers from 1


to 5 using the for statement.

#!/usr/bin/perl

for ($count=1; $count <= 5; $count++)


{
print ("$count\n");
}

Example 2:
Read a line of text, break it into words and print
the words out on separate lines. Assume any of the
following characters may be used to separate
words: blank, ,?"':;. A range of separators can be
passed to split by enclosing them in [].
#!/usr/bin/perl

print("Enter some words: ");


$line = <STDIN> ;

@w = split( /[ ,.?;:"']/, $line);

for ($i=0; $i <= @w; $i++)


{
print ("$w[$i]\n");
}

17

You might also like