+ All Categories
Home > Documents > Unix C-shell Perl Training Document r1.0

Unix C-shell Perl Training Document r1.0

Date post: 18-Jul-2016
Category:
Upload: khanhnam
View: 23 times
Download: 6 times
Share this document with a friend
Description:
Unix C Shell training
36
` Duc Le Page 1 9/15/2008 SILICON DESIGN SOLUTIONS System Administration Group UNIX/C-SHELL PERL TRAINING DOCUMENT Revision 1.0 September 15, 2008 Author: Le Tu Duc
Transcript
Page 1: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 1 9/15/2008

SILICON DESIGN SOLUTIONS

System Administration Group

UNIX/C-SHELL PERL TRAINING DOCUMENT

Revision 1.0

September 15, 2008

Author: Le Tu Duc

Page 2: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 2 9/15/2008

I. UNIX

1. What is UNIX?

- UNIX is a computer operating system originally developed in 1969 by a

group of AT&T employees at Bell Labs.

- Today’s UNIX system are splited into various branches, developed over

time by AT&T as well as various commercial venders and non-profit

organizations.

- Today, in addition to certified UNIX systems, UNIX-like operating system

such as Linux and BSD are commonly encountered.

2. Kernel

- Kernel is the central component of the most operating system. Its

responsibilities include managing the system’s resources (the

communication between software and hardware components).

- As a basic component of an operating system, a kernel provides the

lowest-level abstraction layer for the resources (especially memory,

processors and I/O devices) that application software must control to

perform its function.

3. Shell

- Shell acts as an interface between user and kernel.

- As a UNIX user, you have a choice of shells available to you. These are

the Bourne shell, the C shell, the Korn shell.

4. The directory structure

- All the files in UNIX are grouped together in the directory structure. The

file-system is arranged in a hierarchical structure, like an inverted tree.

The top of the hierarchy is traditionally called root (written as a slash /)

- Example of directory structure:

Page 3: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 3 9/15/2008

5. Starting an Unix terminal

- Terminal is GUI so that user interacts with system.

- Start terminal in UNIX:

- Start terminal in Linux:

Page 4: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 4 9/15/2008

6. Basic commands

Basic commands in UNIX are: mkdir, cd, cp, mv, rm, cat, touch, vi, ls, du, df, pwd, who,

id, chmod, chown, chgrp, top, rlogin, rsh, ssh, ftp, sftp, clear, echo, setenv, tar, gzip, kill,

history, man.

- mkdir: create directory.

- cd: change directory

- mv: move or rename a file or directory

- rm: remove file or directory

- cat: concatenate files and print on the standard output

- touch: create blank file.

- vi: start text editor

- ls: list directory contents

- pwd: print name of current/working directory

- du: estimate file space usage

- df: report filesystem disk space usage

Page 5: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 5 9/15/2008

- who: show who is logged on

- id: print real and effective UIDs and GIDs

- chmod: change file access permissions

- chown: change file owner and group

- chgrp: change group ownership

- top: display Unix/Linux tasks

- rlogin: remote login

- rsh: remote shell

- ssh: OpenSSH SSH client (remote login program)

- ftp: file transfer program

- sftp: secure file transfer program

- clear: clear the terminal screen

- echo: display a line of text

- setenv: add or change environment variable

- tar: the GNU version of the tar archiving utility

- gzip: compress or expand files

- kill: terminal a process

- history: the history command performs one of several operations

related to recently-executed commands recorded in a history list.

- man: format and display the on-line manual pages

� For more detail about above commands, from terminal, type: man <command>

7. VI editor

- The VI editor is a screen-based editor used by many Unix users.

- Some simple VI commands

a enter insert mode, the characters typed in will be inserted after the current cursor

position. If you specify a count, all the text that had been inserted will be repeated

that many times.

Page 6: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 6 9/15/2008

h move the cursor to the left one character position.

i enter insert mode, the characters typed in will be inserted before the current cursor

position. If you specify a count, all the text that had been inserted will be repeated

that many times.

j move the cursor down one line

k move the cursor up one line.

l move the cursor to the right one character position.

r replace one character under the cursor. Specify count to replace a number of

characters

u undo the last change to the file. Typing u again will re-do the change.

x delete character under the cursor. Count specifies how many characters to delete.

The characters will be deleted after the cursor.

:w Write file

:q Exit VI editor

II. C-SHELL

1. About C-Shell

- The C shell (csh) is a developed by Bill Joy for the BSD Unix system. It

was originally derived from the 6th Edition Unix /bin/sh (which was the

Thompson Shell), the predecessor of the Bourne Shell. Its syntax is

modeled after the C programming language. The C shell added many

feature improvements over the Bourne shell, such as aliases and

command history. Today, the original C shell is not in wide use on Unix;

it has been superseded by other shells such as the Tenex C shell (tcsh)

based on the original C shell code, but adding filename completion and

command line editing, comparable with the Korn Shell (ksh), and the

GNU Bourne-Again shell (bash).

Page 7: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 7 9/15/2008

- The C shell has the typical Unix shell structure: each line of input (or line

of a script file) is interpreted as a separate command to execute, with

backslashes "escaping" newlines where needed (so that multiple input

lines can comprise a single command to be executed).

2. Invoking C-Shell

- Each time you log in to UNIX, you're placed in an interactive shell

referred to as your login shell. If your login shell is C shell, you can tell by

its command-line prompt: the percent sign (%). The C shell prompt

differs from the dollar sign prompt ($) of the Bourne shell to remind you

that you're using the C shell.

- If your login shell is not C shell, and C shell is available on your system,

you can invoke it as an interactive shell from the command line. Even

when you're already running the C shell, there will be times when you

want to launch the C shell again, for example to run a shell script or to

temporarily change the shell's options. To invoke the C shell

interactively, use the following command:

$ csh

%

3. Built-in shell command

Command

Description

alias Define or list a command alias

bg Background execution

break Breaking out of a loop

breaksw Exit from a switch statement

case Begin a case in switch

cd Change directory

chdir Change directory

continue Begin the next loop iteration immediately

default Label for the default case in switch

dirs List the directory stack

echo Echo arguments to standard output

eval Rescan a line for substitutions

exec Invoke a new shell

Page 8: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 8 9/15/2008

exit Exit from the current shell

fg Switch a job to foreground execution

foreach Looping control statement

glob Echo arguments to standard output

goto Alter the order of command execution

hashstat Print hash table statistics

history List command history

if Conditional execution

jobs List active jobs

kill Signal a process

limit Respecify maximum resource limits

login Invoke the system login procedure

logout Exit from a login shell

newgrp Change your group ID

nice Control background process dispatch priority

nohup Prevent termination on logout

notify Request notification of background job status changes

onintr Process interrupt within a shell script

popd Return to a previous directory

pushd Change directory with pushdown stack

rehash Rehash the directory search path

repeat Repetitively execute a command

set Display or change a variable

setenv Set environment variable

shift Shift parameters

source Interpret a script in the current shell

stop Stop a background job

suspend Stop the current shell

switch Conditional execution

time Time a command

umask Display or set the process file creation mask

unalias Delete a command alias

unhash Disable use of the hash table

unlimit Cancel a previous limit command

unset Delete shell variables

Page 9: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 9 9/15/2008

unsetenv Delete environment variables

wait Wait for background jobs to finish

while Looping control

%job Foreground execution

@ Expression evaluation

4. Shell programming

a. Shell script

- A shell script is simply a text file containing shell commands.

- Example:

• Create a script ex.csh to print “Hello World!”:

% vi ex.csh

#!/bin/csh -f

echo “Hello world!”

~

% chmod +x ex.csh

% ex.csh

Hello World!

%

b. Variable

- A variable name can consist of only uppercase and lowercase letters and

digits. The name cannot begin with a digit, because names beginning

with a digit are reserved for use by the shell. General usage indicates the

use of all capital letters for the names of environment variables, and all

lowercase letters for local variables, although the shell imposes no such

restriction.

- Use the set/unset statement to create/delete local variables and

optionally to assign a value to them. Local variables are known only to

the current shell and are not passed to shell scripts or invoked

commands.

• Ex:

Page 10: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 10 9/15/2008

set name=a

set name=(a,b,c)

set name[1]=a

unset name

- Use the setenv statement to create new environment variables.

Environment variables are passed to shell scripts and invoked

commands, which can reference the variables without first defining

them (no setenv statement is required or should be used in a shell script

for passed environment variables you wish to access).

• Ex:

setenv $DISPLAY pc150:0.0

setenv $PATH .:/usr/local/bin

unsetenv $DISPLAY

c. Obtaining variable value

Syntax Meaning

$name Replaced with the value of name. It is an error if the ${name} variable name is not defined.

$name[n]

Replaced with the value of elements of array variable ${name[n]}name. For n, write an element

number, or a range of element numbers in the form m-n. Use -n to substitute elements 1-n, and m-

to substitute elements m through the end of the array.

$#name Replaced with the number of elements in array variable ${#name}name.

$?name Replaced with 1 if variable name is set, otherwise 0. ${?name}

d. Array variables

- Assign values to an array variable in one of two ways—all at once, or one

at a time. To assign many values at once, use a wordlist argument to the

set command. A wordlist is a parenthesized list of words.

• Ex:

set name=(a b c) => wordlist

set name[1]=a

set name[2]=b

set name[3]=c

Page 11: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 11 9/15/2008

- Reference the array variable name without an index, the shell replaces

the reference with a wordlist.

- Use the reference $name[*] to obtain all the words of the array without

the surrounding parentheses.

- Reference a specific range of elements using the notation $name[m-n],

where m and n are the beginning and ending index numbers.

- The special form $name[-n] refers to elements of the array beginning

with the first and extending through n.

- The special form $name[n-] refers to the elements of the array beginning

with n and extending through the last.

e. Special read-only variables

Variable Meaning

$0 Replaced with the name of the current shell input file, if known. If unknown, this variable is unset,

and a reference to it is an error.

$?0 Replaced with 1 if $0 is set, otherwise 0.

$1, $2,

...

Replaced with the value of the shell command's first (second, third,_) argument. If used within a

shell script invoked by name, these symbols refer to the command $9 arguments. Up to nine

arguments can be referenced this way. To reference arguments beyond nine, must use the

reference notation $argv[n].

$* Equivalent to $argv[*]. Replaced with all the shell's arguments.

$$ Replaced with the process number of the parent shell. Used within a shell script, refers to the

process number of the invoking shell.

$< Replaced with a line of text read from the standard input file.

- The variables $1, $2, through $9 have special significance when used

inside a shell script, because they refer to the arguments of the

command line that invoked the shell script. The same command

arguments are accessible via the array variable argv. Using the argv

variable, you can refer to all command-line arguments, not just the first

nine. For example, $argv[10] references the tenth argument, and

$argv[$n] references whichever argument is designated by another

variable $n.

f. Operators

- Arithmetic and Logical Operators

Operator Syntax Operation

Page 12: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 12 9/15/2008

~ ~a Bitwise one's complement. The bits of a are inverted so that 1 yields 0, and 0 yields 1.

! !a Logical negation. If the value of a is zero, the value of the expression is 1; if the value of

a is nonzero, the value of the expression is zero.

* a*b Multiplication. The value of the expression is the arithmetic product of a times b.

/ a/b Division. The value of the expression is the integer quotient of a divided by b.

% a%b Remainder. The value of the expression is the remainder from the integer division of a

by b.

+ a+b Addition. Yields the sum of a and b.

- a-b Subtraction. Yields the sum of a and -b.

<< a << b Left shift. Shifts a left the number of bits specified by b. Equivalent to a ´ 2b.

>> a >> b Right shift. Shifts a right the number of bits specified by b. Equivalent to a – 2b.

< a < b Less than. Yields 1 if a is less than b, otherwise 0.

> a > b Greater than. Yields 1 if a is greater than b, otherwise 0.

<= a <= b Less than or equal to. Yields 1 if a is not greater than b, otherwise 0.

>= a >= b Greater than or equal to. Yields 1 if a is not less than b, otherwise 0.

=~ a =~ b Pattern matching. Yields 1 if string a matches pattern b.

!~ a !~ b Pattern matching. Yields 1 if string a does not match pattern b.

== a == b String comparison. Yields 1 if a is identical to b, compared as strings.

!= a != b String comparison. Yields 1 if string a is not identical to string b.

| a | b Bitwise or. Yields the inclusive-or of a and b.

^ a ^ b Bitwise exclusive-or. Yields the exclusive-or of a and b.

& a & b Bitwise and. Yields the and of corresponding bits of a and b.

&& a && b Logical and. Yields 1 if a is true and b is true; otherwise 0 if either is false.

|| a || b Logical or. Yields 1 if either a is true or b is true (or both are true); otherwise 0.

@ @ name=exp

Evaluate an expression and assign the result to a variable, or to an element of an array

variable. The assignment operators +=, -=, *=, /=, %=, <<=, >>=, |=, ^=, and &= are also

supported.

- File testing expressions

Expression Condition When True

-r filename True if file exists and is readable

-w filename True if file exists and is writable

-x filename True if file exists and is executable

-e filename True if file exists

-o filename True if file exists and is owned by the current real user ID

-z filename True if file exists and is zero length

Page 13: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 13 9/15/2008

-f filename True if file exists and is a regular file

-d filename True if file exists and is a directory

g. Statements

- Conditional statements

• if

if (expr) then

commands

else if (expr) then

commands

else

commands

endif

• switch

switch (string)

case pattern:

commands

default:

commands

endsw

- Iterative statements

• while

while (expr)

commands

end

• foreach

foreach name (wordlist)

commands

end

Page 14: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 14 9/15/2008

5. Interpreting a script in the current shell

- Use source to read and interpret a script of shell commands within the

current shell environment.

source name

- For name, provide the filename or pathname of a file containing shell

commands and statements. The shell will search the current directory

path (path variable) for the file if you do not specify a name beginning

with /, ./, or ../.

6. Customizing your shell environment

- The C shell provides for two initialization scripts, the .cshrc and .login

files.

- .cshrc:

• You should define command aliases, variable settings, and shell

options in your ~/.cshrc file (“~”: home directory). It is always

executed before the .login script, and by placing such definitions

in .cshrc, you are assured of having the definitions available in

subshells.

Ex:

if ($?prompt) then

setenv ARCH `arch`

set hostname = `hostname`

set prompt = "`hostname` YOU% "

set history = 100

set savehist = 100

set filec

source ~/.login

source ~/.aliases

mesg n

xhost +

limit coredumpsize 0

Page 15: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 15 9/15/2008

endif

- .login:

• This file should contain defined environment variables such as

PATH, JAVAHOME, …

Ex:

####################################################

setenv OPENWINHOME /usr/openwin

setenv LD_LIBRARY_PATH /usr/local/lib:$OPENWINHOME/lib:/usr/lib

setenv MANPATH .:/usr/share/man:/usr/openwin/man:/usr/dt/man:/usr/local/man

setenv JAVAHOME /usr/java/

####################################################

stty erase '^H'

stty werase '^?'

set path = ( . \

/usr/java/bin \

$JAVAHOME/bin \

/soft/bin \

/usr/ucb \

/bin /usr/bin /usr/sbin \

/usr/local/bin /usr/local/sbin \

$HOME/bin $JAVAHOME/bin \

$OPENWINHOME/bin \

/usr/ccs/bin \

/usr/dt/bin \

/opt/Netscape \

/usr/X11R6/bin \

/sbin \

)

Page 16: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 16 9/15/2008

####################################################

7. Job control

& Execute a command in the background

jobs List active background jobs

wait Wait for specified (or all) jobs to finish

kill Send a signal to specified jobs

bg Resume execution of stopped jobs in the background

fg Switch background jobs to foreground execution

8. Keyboard shortcut keys

CTRL + B Moves the cursor backward one character.

CTRL + C Cancels the currently running command.

CTRL + D Logs out of the current session.

CTRL + F Moves the cursor forward one character.

CTRL + H Erase one character. Similar to pressing backspace.

CTRL + P Paste previous line and/or lines.

CTRL + S Stops all output on screen (XOFF).

CTRL + Q Turns all output stopped on screen back on (XON).

CTRL + U Erases the complete line.

CTRL + W Deletes the last word typed in. For example, if you typed 'mv file1 file2' this shortcut

would delete file2.

CTRL + Z Cancels current operation, moves back a directory and/or takes the current operation

and moves it to the background.

9. Environment variables

a. PATH: specifies directories to search for commands and programs.

- Ex: setenv PATH .:/usr/local/bin:/usr/bin:/soft/bin

b. LD_LIBRARY_PATH: is a colon-separated set of directories where libraries

should be searched for first. This is useful when debugging a new library or

using a nonstandard library for special purposes.

- Ex: setenv LD_LIBRARY_PATH /usr/local/lib: /usr/openwin/lib:/usr/lib

Page 17: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 17 9/15/2008

c. DISPLAY: the $DISPLAY environment variable is used to tell a client to which

server it should send its output.

- Ex: setenv DISPLAY pc150:0.0

In which, pc150 is our machine or which machine that we want to send

output to.

10. xhost, stty commands

a. stty: sets options for a terminal.

- Ex: stty erase '^H' -> sets the erase key to backspace.

- For more detail about this command, type man stty in your terminal.

b. xhost: xhost program is used to add and delete host names or user names to

the list allowed to make connections to the X server.

- Ex:

• xhost + hostname: Adds hostname to X server access control list.

• xhost - hostname: Removes hostname from X server access control list.

• xhost + : Turns off acccess control (all remote hosts will have access to X server)

• xhost - : Turns access control back on.

- For more detail about this command, type man xhost in your terminal.

11. Autocomplete mode

- In C-shell, we can set autocomplete mode to complete our typing.

- To allow autocomplete mode, in terminal, we do: % set filec. From now,

we can use Esc (Unix) or Tab (Linux) to complete our typing.

- Normally, we put above command in ~/.cshrc to enable at first then we

don’t have to set it again.

III. PERL

1. What is Perl?

- Perl is the power and flexibility of high-level programming languages

- Contain control structures and operators similar to C programming

- Ability to write useful programs in a very short time.

- Perl is freeware.

Page 18: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 18 9/15/2008

2. Perl script

- A Perl program consists of an ordinary text file containing a series of Perl

commands.

Ex:

#!/usr/local/bin/perl

print “Hello world!\n”;

� \n: new line character.

3. Data types

a. Scalars

- All numbers and strings are scalars.

- The name of a scalar variable consists of the character $ followed by at

least one letter, which is followed by any number of letters, digits, or

underscore characters (that is, the _ character).

- All Perl variable names, including scalars, are case sensitive. $Name and

$name, for example, are two completely different quantities.

- Perl converts automatically between numbers and strings as required.

Ex:

$a = 2;

$b = 6;

$c = $a . $b; # The "." operator concatenates two ($c = 26)

#strings

$d = $c / 2;

print $d;

yields the result

13

b. Arrays

- A collection of scalars is an array. An array variable name starts with an

@ sign, while an explicit array of scalars is written as a comma-separated

list within parentheses:

Ex:

@machine = ("vsi100", "vsi101", "vsi102");

print “$machine[0]\n”;

Page 19: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 19 9/15/2008

print “$machine[2]\n”;

result in:

vsi100

vsi102

- Mixing scalar types in an array is not a problem.

Ex:

@mix = (2, “How are you?”);

print “$mix[0]\n”;

print “$mix[1]\n”;

result in:

2

How are you?

c. Associative arrays

- Associative arrays are lists of values indexed by strings.

- An associative array name starts with an % sign.

Ex:

%group = (“ns”, ”Network System”, ”is”, ”Intergrated System”, ”hr”,

”Human Resource”);

print “$group{‘ns’}\n”;

print “$group{‘hr’}\n”;

Result in:

Network System

Human Resource

d. File handles

- A file handle behaves in many ways like a variable.

- A file handle can be regarded as a pointer to a file from which Perl is to

read or to which it will write. The basic idea is that you associate a

Page 20: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 20 9/15/2008

handle with a file or device and then refer to the handle in the code

whenever you need to perform a read or write operation.

- File handles are generally written in all uppercase. Perl has some useful

predefined file handles:

File Handle Points To

STDIN Standard input, normally the keyboard. Typically contains everything

you enter when running a program.

STDOUT Standard output, normally the console. Typically stores data that is to

be written to your screen.

STDERR Device where error messages should be written, normally the console.

Ex:

$input = <STDIN>;

print = $input;

If user types:

Hello world

the screen will dislay:

Hello world

Hello world

4. Operators

a. Arithmetic operators

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

** Exponentiation (ex: 9 ** 2 is 81)

% Modulus (ex: 7 % 5 is 2)

b. Comparison operators

String operator Comparison operation Equivalent numeric operator

lt Less than <

Page 21: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 21 9/15/2008

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

- Perl compares strings by determining their places in an alphabetical

order. For example, the string aaa is less than the string bbb, because

aaa appears before bbb when they are sorted alphabetically.

c. Logical operators

Operator Name

&& And

|| Or

! Not

and And

or Or

not Not

xor Xor

d. Some file test operators

Operator Example Name Result

-e -e $a Exists True if file named in $a exists

-r -r $a Readable True if file named in $a is readable

-w -w $a Writable True if file named in $a is writable

-d -d $a Directory True if file named in $a is a directory

-f -f $a File True if file named in $a is a regular file

-T -T $a Text File True if file named in $a is a text file

e. Assignment operators

Operator Operations performed

= Assignment only

+= Addition and assignment

-= Subtraction and assignment

*= Multiplication and assignment

Page 22: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 22 9/15/2008

/= Division and assignment

%= Remainder and assignment

**= Exponentiation and assignment

&= Bitwise AND and assignment

|= Bitwise OR and assignment

^= Bitwise XOR and assignment

Ex:

$a *= 2 => $a = $a * 2

$a %= 2 => $a = $a % 2

f. Operator precddence

Operator Operation Performed

++, -- Autoincrement and autodecrement

-, ~, ! Operators with one operand

** Exponentiation

=~, !~ Pattern-matching operators

*, /, %, x Multiplication, division, remainder,

repetition

+, -, . Addition, subtraction, concatenation

<<, >> Shifting operators

-e, -r, etc. File-status operators

<, <=, >, >=, lt, le, gt, ge Inequality-comparison operators

==, !=, <=>, eq, ne, cmp Equality-comparison operators

& Bitwise AND

|, ^ Bitwise OR and XOR

&& Logical AND

|| Logical OR

.. List-range operator

? and : Conditional operator (together)

=, +=, -=, *=, Assignment operators

and so on

, Comma operator

not Low-precedence logical NOT

and Low-precedence logical AND

Page 23: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 23 9/15/2008

or, xor Low-precedence logical OR and XOR

� For more operators, please refer

http://192.168.100.222/web_books/perl_books/teach_yourself_perl5_21_days/ch

4.htm.

5. Flow control

a. if statement

- Systax:

if (expr)

{

Statement block

}

elsif (expr)

{

Statement block

}

elsif (expr)

{

Statement block

}

else

{

Statement block

}

- Ex:

print “Enter your age:”;

chop ($age);

if ($age < 18)

{

print "You cannot Vote or have a beer, yet.\n";

}

else

{

print "Go and Vote and then have a beer.\n";

}

Result in:

Enter your age:18

Page 24: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 24 9/15/2008

Go and Vote and then have a beer.

b. for statement

- Syntax:

for ( initialise_expr; test_expr; increment_expr )

{

statement(s);

}

- Ex:

for ( $i = 1; $i <= 10; $i++ )

{ # count to 10

print "$i\n";

}

Result in:

1

2

3

4

5

6

7

8

9

10

c. while statement

- Syntax:

while (expr)

{ # while expression is true execute this block

Page 25: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 25 9/15/2008

statement(s);

}

- Ex:

$i = 1;

while ( $i <= 10 )

{ # count to 10

print "$i\n";

$i++;

}

d. until statement

- Syntax:

until (expression)

{ # until expression is false execute this block

statement(s);

}

- Ex:

i = 1;

until ( $i > 10 )

{ # count to 10

print "$i\n";

$i++;

}

e. foreach statement

- Syntax:

foreach localvar (listexpr)

{

statement_block;

}

Page 26: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 26 9/15/2008

� listexpr is any list or array variable, and statement_block is a collection of

statements that is executed every time the loop iterates.

� localvar is a scalar variable that is defined only for the duration of the foreach

statement. The first time the loop is executed, localvar is assigned the value of the

first element of the list in listexpr. Each subsequent time the loop is executed,

localvar is assigned the value of the next element of listexpr.

- Ex:

@words = ("Here", "is", "a", "list.");

foreach $word (@words) {

print ("$word\n");

}

Result in:

Here

is

the

list.

6. Reading from and writing to files

a. Open a file

- Syntax:

open (filevar, filename)

� filevar represents the name you want to use in your Perl program

to refer to the file.

� filename represents the location of the file on your machine

- Ex:

open (TEMP, “temp.txt”);

open (TEMP, “/tmp/temp.txt”);

- File mode:

Read mode Open file to read existing contents only

Write mode (>) Open file to write new contents (overwrite existing contents)

Page 27: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 27 9/15/2008

Append mode (>>) Open file to append contents at end of the file

- Ex:

open (TEMP, “>temp.txt”);

open (TEMP, “>>temp.txt”);

b. Reading from file

- Once we open file, we are able to read from it.

- Ex: a program that reads a file and prints them.

#!/usr/local/bin/perl

if (open(TEMP, "temp.txt")) {

$line = <TEMP>;

while ($line ne "") {

print ($line);

$line = <TEMP>;

}

}

c. Writing to file

- Once we open file to write/append, we are able to write/append to the

file by specifying the file variable with print function.

- Ex:

open (TEMP, “>temp.txt”) || die (“Could not open this file.\n”);

print TEMP (“Hello world.\n”);

Above statement will write to file temp.txt the following content:

Hello world.

d. Closing a file

- When we finish reading or writing a file, we call library function close to

close file.

- Syntax:

close (filevar);

Page 28: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 28 9/15/2008

- Ex:

close (TEMP);

� Perl automatically closes the file when the program terminates or when we open

another file using a previously defined file variable.

7. Pattern matching

A pattern is a sequence of characters to be searched for in a character string. In Perl,

patterns are normally enclosed in slash characters:

/def/

def is a pattern.

If the pattern is found, a match occurs.

a. The match operators

- Perl uses =~ operator to test whether a pattern is matched and !~ to test

whether a pattern is not matched.

- Ex:

$result = $var =~ /abc/

$var is searched for pattern abc, if abc is found, $result is

assigned a nonzero value, otherwise, $result is set to 0.

$result = $var !~ /abc/

If abc is found, $result is assigned to 0, otherwise, $result is set to

nonzero value.

b. Some special characters in patterns

- +: one or more of the preceding characters. Ex: /de+f/ means def, deef,

deeef,...

- [ ]: match one of a group of alternatives. Ex: /d[eE]f/ means /def/ or

/dEf/.

- *: matches zero or more occurrences of the preceding character. Ex:

/de*f/ means df, def, deef, deeef,…

- ?: matches zero or one occurrence of the preceding character. Ex: /de?f/

matches df or def.

Page 29: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 29 9/15/2008

- \: escapes sequences for special characters. Ex: /\*/ means * character is

treated normally, not special character.

- [0-9]: matches any digit between 0 and 9. [a-z], [A-Z] match any

lowercase letter, uppercase letter.

- ^ or \A: match at beginning of string only. Ex: /^def/ matches def only if

these are the first three characters in the string.

- $ or \Z: match at end of string only. Ex: /def$/ matches def only if these

are the last three characters in the string.

- \b: matches on word boundary. /\bdef/ matches only if def is the

beginning of a word. This means that def and defghi match but abcdef

does not. Note that, above pattern will match $defghi because $ is not

assumed to be part of a word, def is the beginning of the word defghi,

and /\bdef/ matches it.

- \B: matches inside word. Ex: /\Bdef/ matches abcdef, but not def.

- .: matches any character except the newline character.

- {}: matches a specified number of occurrences. Ex: /de{3}f/ matches

deeef. /de{1,3}f/ matches def, deef, deeef.

c. Character-range escape sequencesf

Escape sequence Description Range

\d Any digit [0-9]

\D Anything other than a digit [^0-9]

\w Any word character [_0-9a-zA-Z]

\W Anything not a word character [^_0-9a-zA-Z]

\s White space [ \r\t\n\f]

\S Anything other than white space [^ \r\t\n\f]

- Ex: instead of writing /[0-9]/, we can write /\d/

d. Pattern matching options

Option Description

g Match all possible patterns

Page 30: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 30 9/15/2008

i Ignore case

m Treat string as multiple lines

o Only evaluate once

s Treat string as single line

x Ignore white space in pattern

- Ex:

@matches = "balata" =~ /.a/g;

assigns the following list to @matches:

("ba", "la", "ta")

e. The substitution operator

- Syntax:

s/pattern/replacement/

- Ex:

$string = "abc123def";

$string =~ s/123/456/;

So, $string is now: “sbc456def”

Options for substitution operator

Option Description

g Change all occurrences of the pattern

i Ignore case in pattern

e Evaluate replacement string as expression

m Treat string to be matched as multiple lines

o Evaluate only once

s Treat string to be matched as single line

x Ignore white space in pattern

- For example, to change all occurrences of abc to def, use the following:

s/abc/def/g

Page 31: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 31 9/15/2008

f. Translation operator

- Syntax:

tr/string1/string2/

- Ex:

$string = "abcdefghicba";

$string =~ tr/abc/def/;

So, $string is now: “defdefghifed”

Options for translation operator

Option Description

c Translate all characters not specified

d Delete all specified characters

s Replace multiple identical output characters with a single character

8. Subroutines

a. Subroutines

- Like any good programming langauge Perl allows the user to define their

own functions, called subroutines. They may be placed anywhere in our

program but it's probably best to put them all at the beginning or all at

the end. A subroutine has the form:

sub mysubroutine

{

print "Somethings are here\n";

}

regardless of any parameters that we may want to pass to it.

- To call a subroutine, we use & character in front of the name.

- Ex: to call subroutine in above example, we use: &mysubroutine.

b. Parameters

- When a subroutine is called, any parameters are passed as a list in the

special @_ list array variable.

Page 32: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 32 9/15/2008

- Ex:

sub printargs

{

print “@_\n”;

}

&printargs(“arg1”, “arg2”);

Result in:

arg1 arg2

- Just like any other list array the individual elements of @_ can be

accessed with the square bracket notation:

- Ex:

sub printargs

{

print "$_[0]\n";

print "$_[1]\n";

print "$_[2]\n";

}

&printargs("arg1", “arg2”, "arg3");

Result in:

arg1

arg2

arg3

c. 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])

Page 33: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 33 9/15/2008

{

$_[0];

}

else

{

$_[1];

}

}

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

d. Local variable

- We can define local variables for using inside subroutines. These local

variables exist only while the subroutine is being executed. When a

subroutine finishes, its local variables are destroyed; if it is invoked

again, new copies of the local variables are defined.

- Ex:

sub printargs

{

local ($a, $b);

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

$c = $a + $b;

}

$sum = &printargs(1, 2);

print "$sum\n";

print "$a\n"; #Empty

print "$b\n"; #Emty

$a = 1;

$b = 2;

print "$a\n";

print "$b\n";

Page 34: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 34 9/15/2008

Result in:

3

1

2

9. Some functions

a. chop

- Its function is to remove last character from a scalar value.

- Syntax:

chop ($var)

- Ex:

$input = <STDIN>;

print $input; #print which we input and newline character

chop ($input);

print $input; #print which we input

Result in:

%

Hello

Hello

Hello%

b. split

- Its function is to split a character string into a list of elements.

- Syntax:

list = split (pattern, value);

- Ex:

Ex1:

$line = "This:is:a:string";

@list = split (/:/, $line);

Page 35: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 35 9/15/2008

print “@list\n”;

Result in:

This is a string

Ex2:

$line = "This:is:a:string";

@list = split (/:/, $line,3);

print “@list\n”;

Result in:

This is a:string

� In this example, after three elements have been created, no more new elements

are created.

c. sort

- Its function is to sort a list in alphabetical order.

- Syntax:

@sorted = sort (@list);

- Ex:

@list = ("h", "a", "z", "b");

print "@list\n";

@sorted = sort (@list);

print "@sorted\n";

Result in:

h a z b

a b h z

d. Reverse

- Its function is to reverses the order of a list.

- Syntax:

@reversed = reverse (@list);

- Ex:

Page 36: Unix C-shell Perl Training Document r1.0

`

Duc Le Page 36 9/15/2008

@reversed = reverse (@list);

print “@reversed\n”;

Result in:

b z a h

IV. Reference

1. About UNIX and C-Shell, we can refer at:

http://192.168.100.222/web_books/unix_books/unix_book1/index.htm.

2. About Perl, we can refer more advanced at:

http://192.168.100.222/web_books/perl_books/teach_yourself_perl5_21_days/index

.htm and

http://192.168.100.222/web_books/perl_books/perl5_quick_reference/index.htm.


Recommended