Unformatted text preview:

1Perl●Practical Extraction and Report Language●Similar to Python in most senses●Intended to be practical rather than elegant●“There is more than one way”●But easier to write, than to read●Poorly written programs can be almost impossible to decipher●Widely used, so it helps to be able to understand it●Useful for writing short programs to quickly process text files2Running programs●The symbol # is used to comment lines of code●Every statement in perl ends with a semi-colon;●Hello world: print "Hello, world\n";●It is highly reccomended to use warnings and strict syntax:perl -w program.pluse strict●Very hard to discover bugs otherwise and even possible to miss them3Scalars●Can be strings, integers or floating point numbers:my $text = "aeou";my $number = 1;print $text;print "The number is $number\n";●Assignments and operations similar to C:$a = 1 + 2; # Add 1 and 2 and store in $a$a++; # Return $a and then increment it$b = $a; $a += $b; or $a = $a+$b; # Add $b to $a4●Concatenation$a = ‘Monday’; $b=‘Tuesday’;$c=$a.” “.$b;$c= ‘Monday Tuesday’; # Single quote: “don’t do anything to string”$d= “$a and $b”; # Double quote: “interpret any variables in string”print $d; # prints ‘Monday and Tuesday’;●There is a number of special scalars with strange names, that are used for all kinds of purposes.●The most important is the default variable: $_ ●It is the default argument to a number of functions and it's set implicitly by certain looping constructs.●print; # prints the contents of $_5Arrays●List of values:my @animals = ("camel", "llama", "owl");my @numbers = (23, 42, 69);my @mixed = ("aeou", 42, 1.23);●Arrays are zero-based. Single elements are scalars, so $ is used:print $numbers[0]; # prints 23●The special variable $#array gives the index of the last element of an array●Length of an array: (not $#array+1)●@array in scalar context (where Perl expects a scalar value) gives the number of elements in the array:if (@numbers < 5) { ... }6●Initialize an array to null:@colors=();●Functions push and pop#assign elements to array @colors@colors=(“red”,”blue”,”yellow”);#use push function to add an element to the end of arraypush(@colors,”green”);#colors now contains:“red”,”blue”,”yellow”,”green”#use pop function to remove an element from the end of arraypop(@colors);#colors now contains“red”, “blue”, “yellow”7More about arrays●To get multiple values from an array: @animals[0,1]; # gives ("camel", "llama"); @animals[0..2]; # gives ("camel", "llama", "owl"); @animals[1..$#animals]; # gives all except the first element●You can do various things: my @sorted = sort @animals; my @backwards = reverse @numbers;●There are also special arrays, such as @ARGV (the command line arguments) and @_ (the arguments passed to a subroutine).8Hashes●A different name for dictionaries. ●Initialize: %Mygrades=();●Assign elements:$Mygrades{‘CHM696’}=90;$Mygrades{‘CHM621’}=70;●Printing:while(($key,$value)=each(%Mygrades)){print “$key => $value\n”;}●keys() and values() return lists of keys and valuesmy @key_list = keys %hash;my @value_list = values %hash;9●More complex data types can be constructed using references●A reference is a scalar value and can refer to any other Perl data type. ●By storing a reference as the value of an array or hash element, we can create lists and hashes within lists and hashes. References10Conditionals●Testing strings ($a eq $b, $a ne $b):if($a eq ‘red’) { print “the color is $a\n”;}else { print “The color $a is not red\n”;}●Testing numbers ($a == $b, $a != $b):if ($a ==1){$a = $a+2;}elsif ($a ==2) {$a =$a+3;}else { $a++;}●Logicals (&&, ||, !):if(($a==1)||($b eq ‘red’)){print “Color $a is $b\n”;}11Loops●foreach: iterates through the array element by elementforeach $el (@colors) { print “The color is : $el\n”;}for($i=0;$i<=$#colors;$i++) { print “The color is : $colors[$i]\n”;}$i=0;while($i=<=$#colors) { print “$colors[$i]\n”; $i++;}12Files and I/O●Opening a file for reading:$filename =“MyFile.txt”;open(FILE,"/data/MyFile.txt") or die ("Cannot open file MyFile : $!\n");●If the file cannot be opened for reading the program will ‘die’ and the reason will be returned in the special variable $!●To open a file for writing (overwriting):open(FILE,”>OutFile.txt”);●To open for appending: open(FILE,”>>Append.txt”);●Close File: close(FILE);13●You can read from an open filehandle using the <> operator. ●In scalar context it reads a single line and in list context it reads the whole file in, assigning each line to an element of the list:my $line = <INFILE>;my @lines = <INFILE>;●Perl defaults allow for very short programs:while(<>){ print;}●will print whatever it gets from STDIN14#open input file for readingopen(IN,”InFile.txt”) or die “Can’t open file….$!\n”;#open output file for writingopen(OUT,>”OutFile.txt”) or die “Cant open file….$!\n”;while(<IN>){ #while there are still lines in InFile.txt $line=$_; #read in the lines one at a time chop($line); #remove end of line character if($line eq “Number 7”){ print OUT “$line\n”; }}close(IN); close(OUT); #close Files15Regular expressions●A regular expression is contained in slashes, and matching occurs with the =~ operator.●This is true if the string “the” appears in $sentence$sentence =~ /the/●REs are case sensitive, so if $sentence = "The quick brown fox"; then the above match will be false.$sentence !~ /the/ # is true because the (lower case) is not in $sentence●To eliminate case use i:$sentence =~ /the/i; # is true●Special characters are similar to Python. ^ $ * + ? \s \d \n \b16●Besides grouping, parentheses can be used to capture the results of parts of the RE match. The results go to $1, $2, etc.●Example: breaking an email address into parts:if ($email =~ /([^@]+)@(.+)/) { print "Username is $1\n"; print "Hostname is $2\n";}17●Substitution using REs:$sentence =~s/red/blue/; #replaces all instances of red in $sentence to blue●split:$example = “This sentence is split”;@name = split(/\s+/,$example);@name = “This”, “sentence”, “is”, “split”●split can also assign elements to variables:$name = “Bill:Kandylas”;($first_name,


View Full Document

Penn CIS 399 - Perlpython

Download Perlpython
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Perlpython and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Perlpython 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?