PmU(ĥo@K @"Data.app;@O")@ .12 7 Aprintf formatstring, listprintf filehandle formatstring listFIELD TYPE MEANINGc characters stringd decimal integerf floating point numbernb. a - after % indicates left justification @X @XC@Table1 Fun:dDes:dExa:dFor: dp@iTable1ColA1ColB1ColA2ColB2ColA3ColB3ColA10ColB10 Index1ColA1 @ OOOO OOOOfAglob patternChar matches Example? single character f?d matches fud,fid,fdd etc.* any no. of characters f*d matches fd fdd,food etc.[chars] any of characters f[ou]d matches fod and fud but not fad{a,b...} matches either a or b f*.{txt,doc} matches begin with f and end in or .txt or .docA@stuff= stat "myfile";printf "%04o\n", $mode&0777;#the %o is a printf format which prints numbers in expected Octal. The $mode&0777 bit just strips away irrelevant information.print scalar localtime(stat ("foofile"))[9];#prints last modification time of file "foofile"AA -1    F9       0 Asystem commandnb. some commands differ under windows and UNIX (i.e to print a file listing in UNIX is 'ls' and is 'dir' in Windows). If the system function fails non zero is returned (or true!) and vice versa ...this is opposite of what perl usually does.Bdir I sort I more#the contents of dir are passed on to be sorted and then passed on to more (more displays a page at a time)dir /B I sort I perl Totaler I more#Totaler could be a program in perl which prints the directory and some file information.It takes each listing from dir /B and processes it in Totaler which then displays it in 'more'Perl can also treat a pipeline as a file that can be read or written to.eg.open(READHANDLE, "dir/B I sort I ") II die "cannot open pipe for reading: $!";#by having the final I on the right shows that you want the file to be readopen(WRITEHANDLE, " I more") II die "Cannot open pipe for writing: $!";#the I on the left means that Perl is going to write to the pipe.Al%LOLHB %$A6A $ !  A %   @0@PCXC%$AUP] m% ermdirused to remove a directorywprint "Directory to remove?"my $olddir=;chomp $olddir;rmdir ($olddir) II die "Failed to remove $olddir: $!";?7   :rmdir pathname;nb. rmdir only removes empty directoriesf) (unlink&used to remove files from a directoryd#several ways of using unlinkunlink <*.bat>;unlink @badfiles;unlink; #removes the filename in $_?$   Sunlink list_of_files;nb unlink permanently deletes files and cannot be recoveredf<;renamerenames files or directoriesrename "oldfile.txt", "newfile.txt" II warn "could not rename oldfile.txt: $!";also rename can be used to move files:rename "myfile.txt", "/tmp/myfile.txt";#moves the file to the tmp directory?P'(%I!$rename oldname,newname;chmodpA perl command (short for change mode) on the unix platform to give read,write and execute permissions to usersMpLchmod 0755, 'file.pl'#grants RWX to owner,RX to group and non ownersnb. always put a 0 at beginning of mode (above 7 refers to owner, 5 to group and last 5 to non owners)k0gfchmod mode, List_of_files;Per Allows7 read,write,execute6 read,write5 read,execute4 read3 write,execute2 write1 execute0 no permissions          [stata unix based command to find out various file or file handles attributes (its output is different on Unix and Windows platforms).=A stat filehandle;stat filename;^  systemeruns an exterior program through perl.eg. you can run notepad and then return to perl program after.T$file ="myfile.txt";system(edit $file");#in Windows runs an editor on myfile.txt7K)f `dir`QWUnix type function in Perl used to capture output. The ` symbols are called backticks.JW7@dir=`dir`;foreach (@dir){#processes each line of output individually...}another way of representing backticks is to use qx{}:$perldoc = qx{perldoc perl}n 06`dir`3[pipe@used to pass the output from one source as the input to another RInb. UNIX has far more pipe utilties than windows as it relies heavily on them.Architecture NameZa special variable which Perl uses to tell whether its running under Windows or UNIX etc.5if ($^O eq 'MSWin32' {print "Your running windows";}$^Ostring escape sequences%a list of characters such as newline\n newline\r carraige return\t tab\b backspace\u next character to uppercase\l next character to lowercase \character(Afor ($i=0; $i<100; $i++) { next if (not $i % 2); print "An odd number=$i\n";#if $i is even, say 4 then $i%2 is 0 or false. As not false is true then even numbers give true and the next statement is executed (ignores the print part and passes control back to the top of the loop)Aopen(MYTEXT, "novel.txt" II die "cannot open novel.txt: $!\n";an error message may be printed such as:cannot open novel.txt: a file or directory in the path does not exist.If no error message is specified as above then Perl just prints: Died at scriptname line xxx;PM  string literal operator~Saves having to write for example:"I said, \"Go then, \"," i.e. put backslashes before every " to tell perl its a literal "C$ZYaqq( I said, "Go then" )nb. the q operator is the same but works with single ' quotation marks.|H>.qq( )nb qq behaves like "" in every respectf'&modulus0remainder of one number when divided by another24 % 5 the answer is 4%concatenation!joins 2 or more strings together"hello"." world"="hello world".repetition operator,copies a string a specified number of times&$line = "o" x 10;#line = ooooooooooxlengthreturns the length of a stringlength( "nose");#returns 4?f   length(string);; lcreturns a string in lowercase lc ("HELLO");#returns "hello"?f  lc(string); ucreturns a string in uppercaseuc("hello")#returns "HELLO"?f   uc(string);;  rand9returns a random number from 0 to less than its argumentrand(5);#returns 0 to 4?f Nrand(number);nb if a number is omitted a number between 0 to 1 is returned.f? >autodecrement operatordecrease a number by 1$countdown = 10;$countdown - -; #decrease to 9similar to auto increment ++ but adds 1 to numbersame method can be used as +=,*= and %=ie.$r%=67;#divide by 67 and put remainder in $r- -chomp3removes the trailing return character from  $input = ;chomp $input;?Lchomp variablename;;  if....else>controls whether statements are executed based on a conditionif ($r==10){ print '$r is 10';}else { print '$r is not 10';}or for simple code..$correct=1 if ($guess == $question);if (expression) BLOCKif (expression) BLOCK1 else BLOCK2 if (expression1) BLOCK1 elseif (expression2)BLOCK2 else BLOCK3expression if (test_expression);6#Alphanumerica relational operatorska set of operators which examine each element of a string (left to right) and compares their ASCII number.Op explanationeq True ifstring1 and string2 equalgt True if string1 > string 2lt True if string1 < string 2ge True if string1 >= string 2le True if string1 <= string 2ne True if string1 and string2 not equal? &!"!"+    * fstring1 eq string2nb. strings sort in ascending order: punctuation,numbers,Uppercase then lowercaseoR Qlogical operatorsYa set of operators which look at the Truth values of variables and returns true or falseop alternate example&& and $s and $t II or $s II $b! not not $mthe only differences between op and alternate is that II,&& and ! have a higher precedence than and,or,not k      j variousA%G-"  ' f the loop)@ua1u qwhile9repeats a block of code as long as an expression is trueVwhile ($counter < 10){ print "Still counting...$counter\n"; counter ++;}?+ while (expression) BLOCK;for?most versatile loop.Repeats a block while a condition is true.  =clastnb. you can specify which loop is exited by using labels (i.e. INNER: before the inner loop)[nextga statement that gives control back to the top of the loop and the next iteration of the loop to begin(#nextexit.a statement which terminates the perl programEif ($user_response eq 'quit') { print "good bye"; exit 0;}!  9exitnb. exit 0 usually indicates successful completionqwFsaves you having to put quotation marks around each element in a listinstead of having(5, 'apple', $x, 3.1459)useqw( 5 apple $x 3.1459)nb. $x is not treated as a variable using qw , its simply a $ followed by an x. qw( list );range operator,used on literal lists to fill in the rangesx(1..10,20..30)#creates a list of 21 elements (1 through 10, and 20 through 30)(a..z)#creates a list a though to z(number1 .. number 2)M arraya list of elemetnsU@trees= qw (apple, oak,pear, cedar);@fruit = @trees[0,2];$size=@trees; #returns 3@variable_name localtime a function which when acted on as a scalar returns the date and time, and when acted on as a list returns a list of elements that hold the date and time.($sec,$min,$monthday,$month0to11,$years_since_1900,$weekday,$dayofyear,$isdaylight_saving_on)=localtime;#variables above describe localtime localtime0  foreach>function often used with arrays to quickly step through them.Dforeach $cone (@flavours) { print "I want a cone of $cone\n";}?&foreach various uses; split0used to split apart a scalar (usually a string)@words=split(/ /,"The quick brown fox");#The space between / / is used to split apart the sentence and put each word into an array position.\)edjoinWtakes a string and a list and joins the elements of the list together using the stringx$numbers = join (',', (1..10));#assigns the string 1,2,3,4...10 to $numbers. The comma is inserted between each numberJ X sort)takes a list and sorts it in ASCII orderl@cheifs=qw (Clinton Bush Reagan Carter);print join (' ', sort @cheifs);#prints Bush Carter Clinton Reaganz) #  "AOp Result-r True if file readable -w True if filename writeable-e True if file exists-z true if file exists but is empty-s returns size of file in bytes-f True if file is regular-d True if file is a directory-T true if file is a text file-B True if file is binary-M returns days ago that file was modified$filename=;chomp $filename;if (-s $filename) { warn "$filename will be overwritten!";}#A $!+(     #NB/do+g/ matches d then at least one o then g, eg. hounddooooooog/do*g/ matches d then zero or more o's then g, eg. hounddggggh/d.g/ matches d then any one character then g, eg. dug,digger, bad girl/do?g/ matches d then o zero or once then g, eg. dg, puppydog/do{3,6}/ matches do at least 3 times but less than 6 times.eg dododododog(/dogs I cats/) matches dogs or cats/^dogs/ matches dogs only if it occurs at beginning of a line./dogs$/ matches dogs only if it occurs at the end of a linenb. a common match is/first.*last/which matches a first followed by anything then last.A @?H>K%?<66  8 3   1    ?   5 B&0p2p3pppUpWpuq8rrrSrWrvrrRrTR1s4s6ssssPszs|ssssPsSt5uuVupwww`S?q-U a9 9printf:'gives more control over printed words.|printf(%20s", "Jack"); #Right Justify and field is 20 characters$amt=7.127printf("%06.2f",$amt); #prints " 07.13" sprintfzsimilar to printf but instead of displaying an output you can format an output and pass it to a scalar for later display.$weight=85;#format result to 2 decimal places$moonweight=sprintf("%.2f", $weight*.17);print "You weigh $moonweight on the moon.";sprintf formatstring,listpop\removes an element (and returns that element) from the top of an array(also called a stack)k@band = qw( ukelele clarinet);$wind = pop @band;#@band now contains ukelele$wind now contains clarinetpop target_arraypushXpushes an item onto the top of a stack (i.e. adds an element on to the end of an array)f@band = qw( ukelele );push @band, qw( trombone,viola);#@band now contains ukelele, trombone, violapush target_array, new_listshiftRremoves elements from the bottom of a stack (i.e. from the beginning of an array)k@band = qw( trombone, ukelele );$brass=shift @band;#@band now contains ukelele$brass contains tromboneshift target_arrayunshiftCadds elements to the bottom of a stack (the beginning of an array)[@band = qw( ukelele );unshift @band, "harmonica"; #@band now contains harmonica,ukeleleunshift target_array, new_listsplice04used to add or remove elements anywhere in an array@veg=qw(carrots,corn);splice (@veg, 0 ,1); #@veg is cornsplice(@veg,0,0,qw(peas)); #@veg is peas,cornsplice (@veg,-1,1, qw (barley,turnip)); #@veg is peas,barley,turnipsplice(@veg, 1,1); #@veg is peas,turnip#/E)  0#splice array,offsetsplice array,offset lengthsplice array,offset,length,listnb. if offset is a minus then it counts from the end of the array BopendirIused to open a directory on your system.Use / not \ to open a directory.8opendir(TEMPDIR, '/tmp' II die "Cannot open /tmp: $!";opendir dirhandle,directoryreaddir used to read a directory handleopendir(TEMPDIR, '/tmp' II die "Cannot open /tmp: $!";@FILES = readdir TEMP;closedir (TEMP)nb. the entire directory is read into @FILES including . and .. files. To remove these use@FILES=grep( ! / ^ \ . \ . ?$/, readdir TEMP);readdir dirhandle closedir@used to close a directory after it has been opened with opendir[opendir(TEMPDIR, '/tmp' II die "Cannot open /tmp: $!";@files=readir TEMPclosedir (TEMP)?{81closedir dirhandle0 globWNicknamed globbing, another way of opening a file with certain attributes or patterns.Ymy @curfiles = glob( '*1999*.{txt,doc}')#opens text or document files that contain 1999U)0  fchdircchanges the current directory for a perl program(when the program ends the directory reverts back)kprint "Your current directory is : ", cwd, "\n";chdir '/tmp' or warn "directory /tmp not accessible: $!";?y1:!&schdir newdirectorynb. if newdirectory isn't set chdir reverts to the 'home' directory (varies for each computer)F_cwd.used to check what your current directory is.print "Your current directory is : ", cwd, "\n";chdir '/tmp' or warn "directory /tmp not accessible: $!";print "You are now in: ", cwd, "\n";?1:% !5cwdnb. you must type in use Cwd near the start of the program in order to use cwd later on.(Cwd is a module that contains among others the function cwd)  . 5mkdirCreates a new directory}print "Directory to create?"my $newdir=;chomp $newdir;mkdir ($newdir, 0755) II die "Failed to create $newdir: $!";?=   Imkdir newdir,permissionsnb. on windows permissions is 0755 (see chmod)|/(B7o B) V@AXa[Awaabbb9c;c<ccRcYcccdteqfyfff:gggHZiQi{jTlUl\lrlxl=mQmmmsn7oSrWrvrr1s4s6ssssPszs|sss5uuVupwww`qP mspaceship operatortakes 2 operands and returns -1 if its left operand is less than the right, 0 if the 2 operands are equal and 1 if the left is greater than the right.Q@sorted = sort { $a<=>$b; } @numbers;#sorts the array @numbers into ASCII order?\&+ *9<=>nb. to compare alphabetial strings use cmp instead.Z4' reverseua function which given a scalar such as "perl" returns "lrep".When given a list it reverse each element in the list.`@lines = qw( I am Jason Patrick );print join (' ', reverse @lines);#prints Patrick Jason am I#"  filehandlera kind of variable which act as references between your program and the operating system about a particular file.Aopen (MYTEXT, "\Windows\users\novel.txt")II die;close (MYTEXT);?t1( bopen(filehandle, pathname)nb. if a pathname isn't specified Per looks in the current directory.fFE[die>stops execution of a Perl program and prints an error message ?)GBwarnlsimilar to die.It warns you when an action cannot be completed but does not terminate the program like die.eif ( ! open ( MYFILE, "output")){ warn "cannot read output: $!";} else { : #reading output...}"   angle operator <>used to read a filehandlewhile (){ print $_;}#the while reads the entire (opened) MYFILE into $_In a list context each line of the file is assigned to each element of the list or array,eg.open (MYFILE, "novel.txt");@contents = ; 4]  writing to a file >Xwhen a file is opened the > indicates that the file can be written over or appended to.open(LOGF, ">>logfile") II die "$!";if (! print LOGF "This entry was written at ",scalar(localtime), "\n"){ warn "Unable to write to the log file: $!"}close (LOGF);=jopen (filehandle, ">pathname"#overwriteopen (filehandle, ">>pathname"#appendthenprint filehandle LIST(&$"binmodeAs Perl cannot tell the difference between binary data, it interprets every file as a text file. To open picture files etc. you need to use binmode to tell Perl to treat it as binary.2open (FH, ">camel.gif) II die "$!";binmode (FH);?^$ binmode (filehandle);;[file test operators^tests you can perform on filehandle, such as checking if a file exists before overwriting it. #6-X filehandle-X pathnamewhere X is the test letterpattern match operator5takes a string and matches that string with another.s$pat= ;chomp $pat;$_ ="The phrase that pays";if ( /$pat/ ){ print "\" $_\" contains the pattern $pat;\n".  'qm/string/nb. as long as m is used // can be replaced with any other character.If using / / you can omit the m.*A@dogs=qw(greyhound bloodhound terrier mutt chihuahua);@hounds=grep /hound/, @dogs;#hounds now contains (greyhound bloodhound)@newhounds= grep s/hound/hounds/, @hounds;#@hounds now contains (greyhounds,bloodhounds) as does @newhounds. eg. grep with s// also replaces the original array searched@%!Y [metacharactersMsymbols used in pattern matching, which affect which characters are matched. N !character classes3used in pattern matching to find types of strings.[abcde] matches any of a,b,c,d or e[a-e] same as above[Gg] a lower or uppercase g[0-9]+ match one or more digits in sequence[A-Za-z]{5} match any group of 5 alphabetical characters.[^A-Z] match non uppercase alphabetical characters,eg 7,?,q etc.i$,:A  0 X[type]nb. within square brackets metacharacters such as \n become literal characters.special character classesMsymbols used with pattern matching to match groups of particular characters.]/\d{5}/ matches 5 digits/\s\w+\s/ matches a group of word characters surrounded by a space.\w a word character\W a nonword character\d a digit (same as [0-9]\D a nondigit\s a whitespace character [ \t\f\r\n]\S a nonwhitespace character substitutionVa pattern matching operator which also substitutes patterns found with something else7$_="I love Alex";s/love/hate;#becomes "I hate Alex"Xs/pattern/replacement/;nb. the slashes can be any other character. ie s#street#avenuebinding operatorused to bind variables to the special variable $_. Using the $_ variable for a long time is dangerous so we bind a more suitable variable to it. Usually used in pattern matching and replacement.$weight="185 lbs";$weight=~s/ lbs//;#binds weight to $_ (which now contains just 185 as we use s// to substitute lbs for nothing)=~capitals ignorercused in pattern matching and substitution to ignore whether a pattern contains upper or lower caseZ/macbeth/i;#would match macbeth in upper or lower case or both,eg.MaCbeTh would match"s/string/replacement/im/string/iglobal match operatormused in pattern matching and substitution to match one or more times a string or character in an expression.$letters=0;$phrase = "What's my line";while ($phrase =~/\w/g){ $letters++;}#each time a word (ie an alphabet character) is encountered letters is incremented until no more words are found. At the end $letters equals 11.  $s/string/replacement/g;m/string/g;backreferenceswhen using brackets in pattern matching or substitution Perl uses special variables $1,$2,$3 etc. to remember what each part of the pattern is.$_="0044-0114-2796542";if ( /(\d{4})-(\d{4})-(\d{7})/ ) {print "The area code is $2";}#prints The area code is 0114nb. after every pattern match the variables $1 etc. are reset#>!=[grep#used to search arrays for patterns$*?7,+ ~grep expression, listgrep block listnb. grep can also be used without pattern matching eg.@longdogs= grep length($_)>8,@dogs;7$    mapNsimilar function to grep.Can be used to produce a second array from the first@words = map {split ' ',$_} @input;#each element of @input is split apart on spaces producing a list of words. This list is then stored in @words;$p oHashSimilar to an array,but contain 'key - value' pairs.Often used where the key is a unique identifier such as driving licence numbers.%food = (apple => 'fruit', pear => 'fruit', carrot => 'vegetable');to add or refert to a particular key hashes use braces { },eg.$authors{'Dune'}='Frank Herbert';%A$source="One fish Two fish blue fish";$start=0;while (($start = index($source, "fish", $start))!= -1){ print "Found a fish at $start\n"; $start++;}nb the reason that -1 is used above is that if no string is matched the index function returns -1, ie no more fishes found..A"   Je substr'copies a string from some other string$char= substr($line,0,1);# $char now contains character in array position 0nb. if the offset position is negative then the substr counts from the end of the $line?t3X W5substr(array,position,length)substr(array,position)\[indexlfinds a string within another. Often used where the pattern is simple and regular expressions are overkill.&?' 8# |  "{@index string, substringindex string, substring, start position^("rindexSame as INDEX but works backwards from the end of the string.nb start of search position must be after end of last string positiongit is often used in conjusction with LENGTH as this returns the position of the last string character.transliteration operatoran operator which searches through a list and substitutes all the searched string with another string. It is very similar to s/// the substitution operator.>tr/ABC/XYZ#replaces all A's with X's etc.$r= ~tr/ABC/XYZ/;tr/searchlist/replacementlist/Recursive subroutinesFA special class of subroutines that refer to themselves when running.sub factorial { my ($num)=@_; return (1) if ($num<=1); return ($num*factorial($num-1));}print factorial(6);#prints factorial of 6 i.e.6! '.pointers and referencesa reference (or pointer) holds the adress of another scalar variable. To get the actual contents of that variable you dereference the pointer by adding an extra $.$$reference=newValue#wouldchange the realVariables value to the new value.@$reference[2,3] refers to a slice of the array%$reference refers to the whole hashG$reference=\$realVariable$reference=\@realArray$reference=\%realHash@_Fa special variable that contains the arguments passed to a subroutinesub display_score { ($shots,$saves)=@_;print "For $shots shots the keeper made $saves saves";}display_score(10,3);#prints "For 10 shots the keeper made 3 saves"z8/.passing parametersh$bananas=8,$coconuts=5,$fruit=2;sub monkey ($bananas,$coconuts,$fruit)print $_[1];#prints $coconutsπ'bM W9c/rvK " 3"9 ec!2DOFawtGIGKa5v @XgPM ܡ string literal operator~Saves having to write for example:"I said, \"Go then, \"," i.e. put backslashes before every " to tell perl its a literal "C$ZYaqq( I said, "Go then" )nb. the q operator is the same but works with single ' quotation marks.|H>.qq( )nb qq behaves like "" in every respectf'&modulus0remainder of one number when divided by another24 % 5 the answer is 4%concatenation!joins 2 or more strings together"hello"." world"="hello world".repetition operator,copies a string a specified number of times&$line = "o" x 10;#line = ooooooooooxlengthreturns the length of a stringDlength( "nose");#returns 4see substr to limit length of a string?k ' &length(string);; lcreturns a string in lowercase lc ("HELLO");#returns "hello"?f  lc(string); ucreturns a string in uppercaseuc("hello")#returns "HELLO"?f   uc(string);;  rand9returns a random number from 0 to less than its argumentrand(5);#returns 0 to 4?f Nrand(number);nb if a number is omitted a number between 0 to 1 is returned.f? >autodecrement operatordecrease a number by 1$countdown = 10;$countdown - -; #decrease to 9similar to auto increment ++ but adds 1 to numbersame method can be used as +=,*= and %=ie.$r%=67;#divide by 67 and put remainder in $r- -chomp3removes the trailing return character from  $input = ;chomp $input;?Lchomp variablename;;  if....else>controls whether statements are executed based on a conditionif ($r==10){ print '$r is 10';}else { print '$r is not 10';}or for simple code..$correct=1 if ($guess == $question);if (expression) BLOCKif (expression) BLOCK1 else BLOCK2 if (expression1) BLOCK1 elseif (expression2)BLOCK2 else BLOCK3expression if (test_expression);6#Alphanumerica relational operatorska set of operators which examine each element of a string (left to right) and compares their ASCII number.Op explanationeq True ifstring1 and string2 equalgt True if string1 > string 2lt True if string1 < string 2ge True if string1 >= string 2le True if string1 <= string 2ne True if string1 and string2 not equal? &!"!"+    * fstring1 eq string2nb. strings sort in ascending order: punctuation,numbers,Uppercase then lowercaseoR Qlogical operatorsYa set of operators which look at the Truth values of variables and returns true or falseop alternate example&& and $s and $t II or $s II $b! not not $mthe only differences between op and alternate is that II,&& and ! have a higher precedence than and,or,not k      j variousπ'bM@ W9c/rvK O 3"9 ec!2DOFawtGIGKa5v