1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure...

40
1 Programming In UNIX Perl Programming

Transcript of 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure...

Page 1: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

1

Programming In UNIX

Perl Programming

Page 2: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

2

Perl Overview

How to use Perl, quickly: Structure Syntax Data Statements

Page 3: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

3

But first...

Perl Author: Larry WallPractical Extraction and Report LanguagePurpose: UNIX system administrationTwo major characteristics

Rich: Does a lot of things Simple: Easy on the eyes

Ubiquitous: Freely available, versions available for most major operating systems

Page 4: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

4

Recommended Reading

Other Good book: Programming Perl by Wall, Christiansen,

and Schwartz, O’Reilly & Associates, ISBN: 1-56592-149-6

Page 5: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

5

Structure

A compiled - interpreted language Your code is compiled into an internal format,

then interpreted as it runs. You do not need to “compile” it explicitly as you do “c” programs.

A compiler is in the works Currently, you have the source code to run a

Perl program. This is a disadvantage for commercial use where it may violate copyrights to distribute the source.

Page 6: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

6

Structure

Particulars: Don’t declare variables, just use them No data typing: data interpreted in the

context where it is used Data can expand dynamically: You don’t

size arrays UNIX-centric: If you know UNIX, you

know a lot of Perl

Page 7: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

7

Structure

Perl is a procedural language, with object capabilities Statements are executed in sequence,

from top to bottom, unless a branching instruction gets in the way

You can declare and use subroutines, and pass parameters to and from The subroutine is still a good thing to

use...

Page 8: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

8

Syntax

Statements end with a semicolon - “;”White space is an important delimiterYour program ends when the interpreter

reaches the end of the file No fancy “exit” or “end” statements

Use commas to separate operands

Page 9: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

9

Data

Perl is not strongly typed: Whether the contents of a variable are

used as a number or a string depends on the usage itself

If an operator expects a number like + does, then Perl will see the value as a number.

If an operator expects a string like . does, then Perl will see the value as a string.

Page 10: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

10

Data

Perl provides the following data structures: Scalar: single-value - $name Array: indexed list - @names is the array,

$names[1] is an individual value of one cell in the array

Hash: associative array - %person, $person{name}

Variables are “declared” when you first use them Values entered by assignment: $name = “mike”;

Page 11: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

11

Data: Scalars

Some examples$number = 234; # integer$pi = 3.1415; # real$name = “bob”; # string$answer = “My name is $name”; # w/

interpolation$price = ‘$49.95’; #w/o

interpolation$dirlist = `ls`; #command

outputs your directory (*note ` are grave accents)

Page 12: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

12

Data: Scalars

The simplest data that Perl uses Is either a number or a stringNumbers can be integers (whole numbers)

or floating point numbers (i.e. 1.25 or 7.25e45 or -12e-24

String is a sequence of characters within single or double quotes

Statements are terminated by a semi-colonComments starts with a “#”, comment ends

at the end of the line

Page 13: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

13

Data: Scalars

Single quotes - are not part of the string, just to ID the beginning and ending of the string

Exceptions to be aware of: to get a single quote into a string

precede it by a backslash to get a backslash into a string precede

it with another backslash \n for a new line doesn’t work here

Page 14: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

14

Data: Scalars

Double quoted strings. Quotes are still not part of the string but the backslash takes on its full power

String representations (see page 24) \n newline \r return \t tab

Page 15: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

15

Data: Scalars

Operators for Strings the “.” operator concatenates string values

“hello”.”world” shows up as helloworld, you would need “ “ between your values to get a space between i.e. “hello” . ” “ . ”world” gives you hello world

string repetition uses x to take its left operand (a string) and makes as many concatenated copies as indicated i.e. “fred” x 3 gives the output of fredfredfred

Order of operations - Perl follows the normal math method of resolving mathematical operations

Page 16: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

16

Data: Scalars

Two classes of operators: one for comparing numbers, one for comparing strings:

Meaning Numeric StringEqual = = eqNot equal ! = neGreater than > gtLess than < ltGreater or equal > = geLess or equal < = le

Page 17: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

17

Data: Scalars

if I == 5 (by the use of == you know this needs to be a numeric field) Note: you are not giving I the value of 5 you are comparing if I is equal to the value of 5

if name eq ‘jane’ (by the use of eq you know that this is a string

Page 18: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

18

Data: Scalars

Variable - name for a container that holds one or more values, which is what a scalar is

Assignment - way to give a variable a value $name=“mike”

Page 19: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

19

Data: Scalars

Autoincrement old way $a +=1 or new way ++$a

Autodecrement $x=12; --$x the value of $x is now

11

Page 20: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

20

Data: Scalars

The chop and chomp functions chop takes a single argument and removes

the last character from the sting use caution you may only want to remove the

newline at the end of a string chomp removes only a newline character* Note: If you type in a value when you are

assigning a value to a field, and follow that with pressing the enter key, Perl keeps that carriage return as the last character of the value that you just stored

Page 21: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

21

Data: Scalars

<STDIN> means standard inputPerl reads the next complete text

line form standard input and uses that string as the value of <STDIN>. If there’s nothing waiting to be read, the Perl program will stop and wait for you to enter some characters followed by a newline (return).

Page 22: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

22

Data: Arrays

A list is ordered scalar dataAn array is a variable that holds a listEach element of the array is a

separate scalar variable with it’s own value

Can have any number of elementsThe smallest has no elements, the

largest can fill all available memory

Page 23: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

23

Data: Arrays

Some examples: @team = (“bob”, “carol”, “ted”, “alice”);

initializes a four-cell arrayPerl arrays are based at zero: ($team[0] eq

“bob”) is true ($member1, $member2, $member3,

$member4) = @team;reads first four cells into scalars

$team[4] = “bud”;adds bud to the team array

Page 24: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

24

Data: Arrays

qw short for quote word function - creates a list from the nonwhitespace parts between the parentheses

@team = qw(bob carol ted alice); or

@team = qw ( bob carol ted alice);

Page 25: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

25

Data: Arrays

The array elements of team would have the following values

bob = $team[0] carol = $team[1] ted = $team[2] alice=$team[3] bud=$team[4]

Page 26: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

26

Data: Arrays

Other ways to access data in an array [-1] Counts from the back end of an

array so this would give you the value “bud”

# gives the index value of the last element in an array for example print $#team would give the value of 4

Page 27: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

27

Data: Arrays

push and pop will add or remove elements from the right-hand side of an array your array may be set up like this @mylist = (1,2,3); push (@mylist,4,5,6); mylist now has the value (1,2,3,4,5,6) pop@mylistmylist now has the value (1,2,3,4,5)

Page 28: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

28

Data: Arrays

shift and unshift functions perform the same functions as the push and pop, however to the left side of a list shift removes unshift adds

Page 29: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

29

Data: Arrays

The reverse function reverses the order of the elements of it’s argument for example@a=(7,8,9);

@b=reverse(@a); #the value is now #9,8,7 stored in the

array #@b@b=reverse(@b); #gives the reverse of itself

Page 30: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

30

Data: Arrays

The sort functionTakes it’s arguments, and sorts them as if they were single stringsi.e.;

@temp=(2,4,6,8,10,12,14);@y= sort(@temp); # gives

#10,12,14,2,4,6,8

Page 31: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

31

Statements

$input = <> ; #gets input from the keyboard “<>” is the line-reading operator

When empty, refers to all files on the command line, or STDIN if there are none

$input is a variable that we came up withDon’t have to declare itIt’s a scalar variable, denoted by the “$” (more

later)

“=“ assigns the value of the right side to the left

Page 32: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

32

Statements

Try this program: #!/usr/local/bin/perl

print “Enter your name: “;$name = <>;print “Your name is $name\n”;print “…and that’s it.”;

Notice the double-space between the output from the first print and the second in what you see on the screen

Page 33: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

33

Statements

$name contains the response you typed, including the carriage return character.

Insert this statement before the first print: chomp $name; #removes trailing newline

Or, do it like this: chomp($name = <>);

Page 34: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

34

Statements: If

if (condition) {statements} # if statement

{…} is a block; don’t need “;” after itExample:

if ($input eq “yes”) { print “Okay, I’ll do it”;}else { print “Heck no, I won’t do it”;}

Page 35: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

35

Statements: While

while (condition) {statements} #while loop

Don’t forget to insure the condition eventually evaluates to false in the loop

Example: while ($input ne “rumplestiltskin”) {

print “Enter it until you get it RIGHT: “; chomp ($input = < >);}

Page 36: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

36

Statements: For, Foreach

for ($i = 1; $i < 10; $i++) {print “$i\n”;}foreach $name (@class) {print “$name\

n”}; foreach VAR (LIST): iterates through the

LIST, putting the next element in VARforeach $name ( sort values %team )

{print “$name\n”;} values is a subroutine that returns a

list of the values contained in %team sort is a subroutine that sorts the list of

values

Page 37: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

37

$_: The Default Input

A global special variable: it’s already there $_ is assumed in a lot of places where you

could put a variable, but choose not to: while (< >) { # reads into $_ print; # prints $_ foreach (%name) { # each value from

#%name goes in $_ Good and Bad:

Good: provides brevity of expression Bad: Not intuitively obvious what is being

manipulated...

Page 38: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

38

Built-In Function: Split

($name, $grade) = split /:/, $line; split /PATTERN/, EXPR

/PATTERN/ is the delimiter to recognize in splitting

EXPR is the string to be split

Above would take a value of $line like “bob:40” and put “bob” in $name and “40” in $grade. The delimiter is lost in this case.

Page 39: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

39

Built-In Function: Open

open (MYFILE, “thefile.txt”); Opens the file so named, assigns

it to a file handle for subsequent use

You can write a short-circuit version of an if statement like this: open (STUFF, “stuff”) or die

“Can’t open stuff”; die is a function that causes an

orderly exit from the program, writing a message to stderr

Page 40: 1 Programming In UNIX Perl Programming. 2 Perl Overview zHow to use Perl, quickly: yStructure ySyntax yData yStatements.

40

Lab1 - Hints

How do you invoke a system command from within Perl? There are two ways. system

system “who”; exec

exec “who”;