Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP234 Perl Printing Special Quotes File Handling.

Similar presentations


Presentation on theme: "COMP234 Perl Printing Special Quotes File Handling."— Presentation transcript:

1 COMP234 Perl Printing Special Quotes File Handling

2 Perl Documentation Can be found here: –http://perldoc.perl.org/http://perldoc.perl.org/ The bulk of the reference material is in: –http://perldoc.perl.org/index-functions.htmlhttp://perldoc.perl.org/index-functions.html You can find that link under Reference/Functions Also important: –Language –Operators –Special Variables

3 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

4 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

5 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

6 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.

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

8 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

9 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

10 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”

11 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

12 printf You can also specify "flag modifiers": %10s = right justified 10 character string %8.2f = right justified 8 character floating point number where max field length is 8 characters, includes a character for 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.

13 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"

14 OUTPUT Volume in drive D is HONKER2 Volume Serial Number is 2047-15DB Directory of D:\Perl\my.pl 01/22/2008 09:49a. 01/22/2008 09:49a.. 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

15 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

16 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.

17 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.

18 Examples $str=<<EOF; A line to print\n “EOF” print $str $str=<<EOF; A line to print\n 'EOF' print $str

19 Examples $str=<<EOF; dir `EOF` print $str Try these in the lab

20 File Processing

21 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

22 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

23 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

24 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

25 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

26 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

27 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.”

28 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”

29 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

30 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 $!)

31 Working with files In scalar context, evaluating a filehandle in angle brackets yields the next line from that file $line = You can assign the entire file to an array –@lines = And then print it – print “@lines”

32 Lab this week A simple lab to explore the perl working environment and create a hello world program


Download ppt "COMP234 Perl Printing Special Quotes File Handling."

Similar presentations


Ads by Google