Perl Backticks Hashes printf Variables Pragmas
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: print "$str\n"; print
OUTPUT Volume in drive D is HONKER2 Volume Serial Number is DB Directory of D:\Perl\my.pl 01/22/ :49a. 01/22/ :49a.. 01/22/ :53a 72 test.pl 01/22/ :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
Hashes
Also known as associative arrays Arrays start –Contain a list of values –Values referenced by a subscript –$array[3] refers to the fourth element Hashes start with % –Contain a list of key - value pairs –Key used to retrieve the other value –$age{"Fred"}
hash Example The value used to retrieve is called the key $age{"Fred"} =10 –stores 10 in the hash %age using key "Fred" Note the use of $ when referencing a single value from the hash Can create from a list –%age = ("Fred", 10, "Sue", 8)
Hash operators $hash{"key"} = "value" –adds record with key "key" and value "value" keys(%hash) –returns a list of the key values, random order values(%hash) –returns a list of the values, same random order delete $hash{"key"} –removes the record for key "key"
Looping through a hash To operate on all the records in a hash: foreach $key ( keys(%hash) ) { print $hash{$key}; } foreach $var list {block} Assigns each value in list to $var, then runs block Does this once for each value in list
Looping through a hash To operate on all the records in a hash: while (($key,$value) = each(%hash)) { print $value } Note that "each()" gets a row from the hash in the same way that gets a line from a file Rows from the hash are lists Once end is reached, returns empty list Empty list is false, other lists are true
More reading Read the chapter on hashes in your selected text You can find much of the material under /pod/perlfunc.pod /pod/perlfunc.pod Look for the functions mentioned in the lecture –each, keys, values, delete
printf
Used to provide more control over the format of printed output Particularly numbers Uses “format specifier” strings to specify how data are to be printed
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
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.
Variables
Variable Names The name of a variable consists of the character $ or %) followed by at least one letter or underscore, which is followed by any number of letters, digits, or underscore characters. The following are examples of legal variable names: –$x –$_x –$var –$my_variable –$var2 –$a_new_variable
Variable Names These, however, are not legal variable names: –variable # the $ character is missing –$ # there must be at least one letter –$47x # second character must be a letter –$variable! # you can't have a ! in a variable name –$new.var # you can't have a. in a variable name
Variable Names Variable names should be meaningful –$LineCount – is better than $Count Meaningful names make programs more understandable Therefore easier to debug
Good Variable Names Variables answer a question about a thing Names should tell you the what the thing is and what the question is $count –Bad, what is being counted? $RecordCount –Better, but what records? $LogMessageCount –Better still, relates to actual contents of record
Variable Names Perl variables are case-sensitive. This means that the following variables are different: –$VAR –$var –$Var Initial caps is a useful convention for long names –$MultiWordName Some prefer Underlines –$Multi_word_name
Declaring Variables Perl variables don't have to be pre-declared But if you do, perl can warn you when you spell a name wrong my variablename Declares variablename and makes it a private variable This line, at the top of your template file, turns on warnings, and is a good idea. #!perl -w You should use this in future programs
Pragmas
Modules that change behaviour of compiler Some change the behaviour of the interpreter use integer Others enforce good programming
Use Integer Causes perl to employ integer arithmetic by default Remains in effect to the end of the block An inner block can override using: no integer; which remains in effect to the end of the inner block
Use Integer Example $x = 120/7; print "$x\n"; use integer; $y = 120/7; print "$y\n"; cmblap:~ # perl test2.pl
Use Strict You should start every program with use strict –Put it at the top of your template use strict 'refs' Generates runtime error if you use any symbolic references. use strict 'subs' Generates compile-time error if you use a bareword identifier that's not a predeclared subroutine. use strict 'vars' Generates compile-time error if you access a variable that wasn't declared via my, isn't fully qualified, or wasn't imported.
use warnings Similar to -w but more complicated –Can be fine tuned –Can apply only to a block –Can be turned off and on Most of the time -w is preferred