comp234 perl printing special quotes file handling

32
COMP234 Perl Printing Special Quotes File Handling

Upload: reynold-craig

Post on 17-Dec-2015

221 views

Category:

Documents


1 download

TRANSCRIPT

COMP234 PerlPrinting

Special QuotesFile Handling

Perl Documentation

• Can be found here:

– http://perldoc.perl.org/• The bulk of the reference material is in:

– http://perldoc.perl.org/index-functions.html

• You can find that link under Reference/Functions

• Also important:

– Language– Operators – Special Variables

Working with Perl

• Edit the source code with a text editor (not a word processor)

• Don't copy snippets from word documents

• Use three windows

– A command prompt, cd to working dir– Your text editor– A file manager viewing your working

directory• You can usually drag and drop file to editor

– And to the command prompt

Functions in perl

• In perl, everything is a function

– Even things that look like commands

• Everything returns a value

• Functions can have effects other than just returning a value or changing the argument values

• Parentheses are optional

Interpolation

• When using single quotes all characters are treated as literals.

• When using double quotes, almost all characters are treated as literals.

• But some things are not. • These exceptions are “interpolated” into the rest of the

literal. – Escape sequences

– Variables

Variable Substitution

• Example:$Word1 = "thank";

$Word2 = "you";

$Sentence = "I just wanted to say $Word1 $Word2.";

print $Sentence;

• Program Output:I just wanted to say thank you.

Variable Substitution

• Program Output:

– I just wanted to say thank you.

• Perl evaluates each variable and interpolates it directly into the literal

• Notice that when the print statement displays the contents of $Sentence, it inserts a space between the two quoted words and inserts the period at the end.

• Perl evaluates the variables and interpolates the values but leaves other characters, such as spaces, exactly as you enter them.

Another Built-In Variable

• We looked at $_, $, $/ $”

• Variables that start with $ are scalars

– Single valued

• Variables that start with @ are arrays

– A list or table of values

• @INC is an array of file system paths

• Each path is the location of a perl library that will be searched at run time to find included perl modules

perl -e

• perl has the useful ability to run short programs without first saving them to a file

• perl -e “text”

– runs text as a perl program

• perl -e “print 2 + 2”

– Prints 4

Printing @INC

• Perl -e "print \"@INC\""

E:/PortableApps/perl/perl/lib E:/PortableApps/perl/perl/site/lib

• @INC is interpolated into double quoted string• $” is inserted between array elements• $” contains a space• The \ tells DOS to ignore the following quote• Otherwise the program would end at the second quote

• Actual program is: print “@INC”

printf

Example:printf("The name is: %10s\nThe number is: %8.2f\n","Ellie", 33);

The printf function prints a formatted string Comma separated arguments are substituted into the string before printing.

Perl uses a "format specifier" character ("%x") in order to specify how to print the variable value when it has been substituted.

For example: %s = string

%f = floating point number%c = character

printfYou can also specify "flag modifiers":

%10s = right justified 10 character string%8.2f = right justified 8 character floating point number wheremax field length is 8 characters, includes a characterfor a decimal point, followed by 2 digits.

Example:printf("The name is: %10s\nThe number is: %8.2f\n","Ellie", 33);

Program Output:The name is: Ellie

The number is: 33.00

Don't fall into the trap of using a printf when a simple print would do. The print is more efficient and less error prone.

Backticks• Strings enclosed in backticks are treated as DOS

commands

• String is executed in a dos shell

• Result is interpolated in place of the string

• See Operators, search for backticks

• Example:

$str=`dir`;

@tab=`dir`;

print "$str\n";

print "@tab"

OUTPUT

Volume in drive D is HONKER2

Volume Serial Number is 2047-15DB

Directory of D:\Perl\my.pl

01/22/2008 09:49a <DIR> .

01/22/2008 09:49a <DIR> ..

01/22/2008 09:53a 72 test.pl

01/22/2008 09:54a 0 test.out

2 File(s) 72 bytes

2 Dir(s) 1,442,611,200 bytes free

Here Documents• A way of specifying multi-line literals

• See operators, search for Here Document

• Example:

$str =<<EOF

This is a long litteral

It is three lines long

This is the third line

EOF

print $str

This is a long litteral

It is three lines long

This is the third line

Here Documents

• If the terminating string is quoted, the type of quotes used determine the treatment of the text.

• Double Quotes– Double quotes indicate that the text will be

interpolated using exactly the same rules as normal double quoted strings.

Here Documents

• Single Quotes– Single quotes indicate the text is to be treated

literally with no interpolation of its content.

• Backticks– The content of the here doc is treated just as it would

be if the string were embedded in backticks. Thus the content is interpolated as though it were double quoted and then executed via the shell, with the results of the execution returned.

Examples

$str=<<EOF;

A line to print\n

“EOF”

print $str

$str=<<EOF;

A line to print\n

'EOF'

print $str

Examples

$str=<<EOF;

dir

`EOF`

print $str

• Try these in the lab

File Processing

File Processing

• You must open a file before you can process it• Opening associates a FILEHANDLE with a file• Outside the perl program files are known by their

paths– c:\myprograms\mytestdata.txt

• Inside a perl program an open file is known by its FILEHANDLE

Open Function

• open FILEHANDLE,EXPR• open FILEHANDLE,MODE,EXPR• open FILEHANDLE• ...• Lots of format options• You will normally use:

– open FILEHANDLE,MODE,EXPR

• Or – open FILEHANDLE,EXPR

Open Function

• open FILEHANDLE,MODE,EXPR• FILEHANDLE is an identifier of your choice,

conventionally all upper case:– INPUT MYFILE SALES

• MODE indicates intended usage– “<” -- input– “>” -- output (Creates file or overwrites)– “>>” -- append

• EXPR is the path to the file, or a variable

Open Function Variations

• open FILEHANDLE,EXPR• MODE can be omitted,

– default is “< “meaning input

• Or mode can be the first character in expression– Open OUTPUT, “> c:\data\output.txt”;

• FILEHANDLE can be contained in a variable– Open $handle, $filename

Error Handling

• When dealing with files:–Always be prepared for the unexpected–You can't control the state of the disk when the program is

run– So you have to be prepared for non-existent files

Error Handling

• Die function:– die LIST

– Prints the value of LIST to STDERR and exits with the current value of $! (errno).

• Exiting with die is the normal means of handling file processing errors

• There is usually nothing else you can do

ERRNO

• $!

• if a system or library call fails, it sets this variable

• See Perl special variables– http://perldoc.perl.org/perlvar.html

• $! returns different value depending on context

• If die $! yields – “No such file or directory at files.pl line 2.”

• die abs($!) yields– “2 at files.pl line 2.”

Die Variations

• With or without line feed:

• die $! yields

– No such file or directory at files.pl line 2.

• Die “$!\n” yields

– No such file or directory

• If you don't specify \n,

– perl adds “at $program_name line $line_number \n”

Open with Error Handling

• open MYINPUT , “<input.txt”

or die “Can't open input.txt” , $!;

Opens file or prints message and quits.

Quitting is the usual response to file errors

open or die Variations

• “||” instead of “or”:

• or and || both mean “or” but “or” has higher precedence

• open IN, “file” || die $!; doesn't work

• It is interpreted as

– open IN, (“file” || die $!)

• open IN, “file” or die $!; does work

• It is interpreted as

– (open( IN, “file”) or die $!)

Working with files

• In scalar context, evaluating a filehandle in angle brackets yields the next line from that file

• $line = <MYINPUT>

• You can assign the entire file to an array– @lines = <MYINPUT>

• And then print it– print “@lines”

Lab this week

• A simple lab to explore the perl working environment and create a hello world program