Lecture 11

Scalar data in Perl

Perl Control Structures

Strings vs. Words

Counters in Perl

File Management

Match Operators

 

A Stroll through Perl: Starting up

#!/usr/bin/perl -w

print ("Hello, World\n");

Scalar Data

Hello, $name

where $name is the user’s name

 

Using a Scalar Variable

#!/usr/bin/perl -w

print ("What is your name?\n");

$name = <STDIN>;

chomp ($name);

print ("Hello, $name\n");

same print statement as hello

<STDIN> grabs one line of input from the screen

$name holds this input

$name is known as a scalar variable

Adding a Condition

if (condition) {

action;

}

parentheses are required around the condition

curly braces are required around the action

if then else

if (the gas is low) {

buy more;

} else {

continue driving;

}

The effect of the if condition

gas is low buy more

if

gas is high continue driving

The flow of the program can go in either direction

Control Structures

The notion of a ‘string’

continent a new nation conceived in liberty

in this quote

 

The need for a string counter

grep Powell ap.stories

asked Powell. Powell replied that he would

grep returns the line with multiple ‘Powell’s

tr -cs [A-z0-9] $1 | sort | uniq -c

43 Powell

gives the answer but with a lot of extra unnecessary computing and no context

.

A Perl Counter

 

Writing a Perl Program

 

Filehandles

$name = <STDIN>;

(FH, "$ARGV[0]")

Filehandles (2)

(FH, "$ARGV[0]")

findwd.pl gettysburg

$ARGV[0] is the file gettysburg

 

Opening a file

open (FH,"$ARGV[0]")

Non-existent files

die

"cannot open"

die "cannot open"

How Perl reads from a file

$line = <FH>;

Getting a Perl script to read from a file

open (FH,"$ARGV[0]") || die "cannot open";

while ($line = <FH>)

or stop the program and report failure

The =~ operator

$name = <STDIN>

$a = "fred"

$line =~ /in/

$line =~ /[Jj]ohn/