Perl - Murray State University

Download Report

Transcript Perl - Murray State University

Perl

Programming with the “Swiss Army Chainsaw” of scripting languages

Starting Simple

We will start presuming you have already installed a Perl interpreter such as strawberry If using linux you need to start your file with

#!/usr/local/bin/perl

It wont hurt if you are in practice of doing that even for windows but it is not necessary Save your file as filename.pl

Open your Perl interpreter command prompt and navigate to the file directory you have saved your file and type

perl filename.pl

Hello World

#literal interpretation print 'Hello\nWhat is your name?\n'; #interpreted print "Hello\nWhat is your name?\n";

Variables

• • A quick note: All variable names are a punctuation character, a letter or underscore or one or more alphanumeric characters or underscores Scalars are things such as a number or a string. • • • When Perl needs to treat a scalar as a string it does.

When it needs to treat it as a number, it does.

The conversion happens automatically

Scalars as numbers

• • $n =5; $n = $n + 5; • $a = $n * 10; • $a++; • $n /= 2; # $n is now equal to 10.

# $a is equal to 100.

# $a is now equal to 101.

#$n is now 5.

Skipping ahead and saving lives a subprogram

#this is a function for printing line so you don’t have to #Print “\n”; after every scalar to keep things separate.

sub println { print ((@_? join($/, @_) : $_), $/); }

This note was added for anyone trying to follow along with this slide.

$p = "1"; println $p;

Concatatenation

# $p is a string $x = $p + "4"; println $x; # "4" is a string $y = $p . "4"; println $y; # x and y have two different values

Scalars as Strings

$pizza_price = 11.99; $special_of_the_day = "one large $n topping pizza for ".'$'."$pizza_price"; print “ Today's special is $special_of_the_day.\n";

Arrays

@pizza_toppings = ("pepperoni", "green pepper", "ham", "bacon", "onion"); #this is just an example to show the numbering starts at 0 print $pizza_toppings[1]; print "\n"; print $#pizza_toppings+1; print "\n";

Loops and Arrays

} @p_top = ("pepperoni", "green pepper", "ham", "bacon", "onion"); for $i (0 .. $#p_top) { println $p_top[$i]; $#p_top = 0; # now the array size has changed to 1

$p_top[1] = "ham"; $p_top[2] = "bacon"; } $p_top[3] = "green pepper"; $p_top[4] = "onion"; for $i (0 .. $#p_top) { println $p_top[$i];

Inside an Array

for $i ('ham', 'bacon', 'green pepper', 'onion') { $count += 1; } $p_top[$count] = $i; } for $i (0 .. $#p_top) { println $p_top[$i];

Comparison

• • • For strings we use eq to compare equality.

For numbers we would use == for comparing equality.

Ex: unless ($topping eq 'pepperoni') { } else { println "I dont want $topping pizza."; println "$p_top[0]!, my favorite!" } $topping = pepperoni; $topping = ham;

More Comparison

• Perl comparison statements • While #while (x < a) • Until #until (x == a) • If #if (x != a) • Unless #unless (x == a)

More about Strings substr()

$s2m = "a string to manipulate"; # substr(sentencegiven, startingposition, startingposition+number) println substr($s2m, 0); # i might as well have said println $stm; # whats happening next is i am going from location 0 and grabbing the next 5 characters.

println substr($s2m, 0, 5); # result would be >a str # whats happening here is i am going to location 4 and grabbing 4 characters.

println substr($s2m, 4, 4); # this result is >ring # here we start from 4 from the end of the sentence println substr($s2m, -4); # result >late #both of the next two give result >man println substr($s2m, -10, -7); println substr($s2m, -10, 3);

More about Strings split()

} # now how to split a string apart with spaces @s2m = split(/ /, $s2m); for $i (0 .. $#s2m) { println $s2m[$i]; } # here we split it in 3 @s2m_2 = split(/ /, $s2m, 3); for $i (0 .. $#s2m_2) { println $s2m_2[$i];

More about Strings join()

# how to join words in an array into a string $s2j = join(' ', @s2m); println $s2j; # how to join a string with other strings $stringjoiner = ' with '; $s2j = join($stringjoiner, @s2m); println $s2j;

File Handling

• • • • • • • • • • • • • We have with Perl the ability to open() a file.

The LOGFILE would be what we use in the program to access.

The name of LOGFILE, OVERWRITE, APPEND could be ANYTHINGYOUWANT.

The only thing telling Perl what you are doing with the file you are opening • is the > means you are overwriting >> means you are appending and nothing means you are just opening the file to use.

open (LOGFILE, "log.txt"); open (OVERWRITE, ">overwrite.txt"); Overwrite would destroy any information already in the file.

open (APPEND, ">>append.txt"); Appending would simply add to the end of a file.

Perl will create a file if its not there and and open it if it is.

Perl will also automatically close the file when you close Perl To make cleaner code you should close it yourself with close LOGFILE, or whichever file name you are using.

You can add or die to the end of any of the open statements and a message to go with it.

• This is so that if the open() call fails it will do the or option and die giving you the error message from Perl and if you added a message • • In addition the message you wrote with it would be given as well. There is also an and position in Perl which allows you to add other measures to process.

Subprograms

• Whenever you call a subprogram it will take parameters you pass to it and can return values just as a built in Perl function would.

• Any parameters you pass to it are placed in the special array @_ • You can return any single value or list using the return keyword.

• Also in a subprogram it is smart to use the my keyword • my will allow you to use otherwise used names of variables in the rest of the program without changing any values of them.

• In other words if you have $x as a parameter outside the subprogram • You could use the my keyword so that it wouldn’t overwrite it.

• Or you could purposely overwrite it inside the subprogram for an outside variable.

Regular Expressions

• • The simplest regexes matching expressions.

You can find if an entire file or string contains the word the • $filename =~ /the/ # you could find any regular expression • Then you could do something with that knowledge.

*Metacharacters are characters with special meaning such as ^ meaning the beginning of a string and $ meaning the end of the string.

* /^Now/ would match Now we begin.

it would not match and Now we begin.

Here is a way to grab URLS if ($line =~ /^http:/) print $line; Here is a way to grab gif files if ($line =~ /gif$/) print $line; *Wildcards are also used. You can use . to match any character other than newline if you don’t want to use the wildcard and mean it to find a literal . you must add \ to it such as .\ would be meaning find the . Instead of finding any character

Regular Expressions cont.

• • An addition wildcard is \d to find a single digit.

You can match multiple numbers /\d{3}-d{4}/ would give you a phone number searching criteria.

• • • • This type checking reminds me of SQL.

You can give a range of numbers to find /\d{1,99}/ You can use \D to find anything not a digit Similar things can be done for • \s which is white space \S anything but white space • \w any letter, digit or underscore \W anything else • /[^a]/ would find anything except a lowercase a • /a/i would find any lowercase a