1. LON-CAPA Logo
  2. Help
  3. Log In
 

Perl

Back to Index

There are quite a few things that you are able to do in Perl, and the more ways you know to edit data, the more you are able to do. This section will help expand your knowledge of Perl, giving you the tools needed that will allow you to manipulate data in several ways, or formats. This is most useful in custom response problems, where by design you have more freedom in processing user input.

At the most basic level, Perl reads instructions and executes them. The instructions are the code that you write. The character “;” signifies the end of an instruction. There are also other ways to signal where instructions begin and end, but we’ll get into that later. The computer reads line by line and executes each instruction one at a time, except for the special cases which are called control structures. It is important to keep in mind the order that your code is executed, otherwise you might get unexpected behavior.

 

Variables

A variable is a place where you can store data. A variable in Perl is denoted by “$” attached to the name of your variable. You must begin a variable name with a letter, and generally the only characters included are letters and numbers since other characters can break your code by making the computer think your variable is something else. Variables in Perl considered by the computer to be both numbers and words depending on what you do with them.

$num = 2;
$greeting = “hi :)”;

As shown in the example, the characters “” signify the beginning and end of a set of characters commonly called a string. A string is a set of characters ordered in a particular way. Using “” shows the computer that whatever is contained is a string as opposed to a number. However, if you have erroneous characters outside the “” then it will cause errors.

$greeting = “hello” 2;

In this example there is no clear type of input, so the computer doesn’t know what to do, so it tells you there is an error when you try to run this code.

You can add variables and set them to another variable in several ways. The following are mathematical operators that can be performed.

$ans = 1+1; #This equals 2
$ans = $ans + 1; #This equals 3
$ans = $ans * $ans; #This equals 9
$ans = $ans * $ans; #This equals 9

$hello = “friend”;
$number = 2;
$ans1 = “hello $hello” ; #ans1 contains the string “hello friend” without the “”
$ans2 = $ans1 . $number; #ans2 contains “hello friend2”
$ans1 = “hello$hello” ; #ans1 contains the string “hellofriend”. Notice the missing space
$ans2 = $ans1 . $number; #ans2 contains “hellofriend2”
$number = “$number$number”; #number now contains “22”

One important part of using variables is checking them to make sure they aren't going to cause "bad answers" that may error out or have long unwanted decimal places. To do this, you may use a do-while loop. See the Loops section below for more information.

Rounding

To properly accept rounded answers in LON-CAPA, you will need to round the calculated answer using the sprintf command. 

Example:

$craw=$pka + &log10($b/$a);
$c = sprintf("%.2f", $craw);   <<<< This line will round the value for $craw to 2 places right of the decimal.

Accepted formats are:

 

  <num format="2E">31454678</num> results in 3.15 x 10^7
  <num format="2f">31454678</num> results in 31454678.00
  <num format="4g">31454678</num> results in 3.145 x 10^7
  <num format="4g">314.54678</num> results in 314.5
  <num format=",2f">31454678</num> results in 31,454,678.00
  <num format="$2f">31454678</num> results in $31,454,678.00
  <num format="2s">31454678</num> results in 31000000
  <num format=",2s">31454678</num> results in 31,000,000

Arrays

 

Another way to save data is an array. An array contains several variables.

@myFirstArray = (1,2,3,4,5);

‘myFirstArray’ now has 5 variables. To get these variables, you would look for the variable inside the array by index. The first variable has an index of 0 and each subsequent variable is one greater than the last. You ‘look’ inside the array by using [].

@myFirstArray[0] #contains 1
@myFirstArray[1] #contains 2
$var = @myFirstArray[1] + @myFirstArray[4]; #$var is 7

Comments

One way to control what is being read by the computer is to use comments. Comments offer a way to communicate to others that are reading your code without editing what the computer reads. They do this by keeping lines of text in the code that are not executed, allowing you to give instructions to those who may want to edit your code in the future. Writing a comment is very simple. Adding the “#” character inside of a Perl script tells the computer to not read anything else on that line. For example:

$ans = 1; #this sets the answer to one

This is a good way of explaining what is happening in your code when your code starts to get complicated.

However, you must be careful to make sure that you do not comment out important parts of your code. For example in the code,

if ($condition==true){#do stuff}

the last character } will also be commented out. Since the computer does not know where to end this if statement, the code will not run.

Control Structures

Control structures are able to tell a computer to stop reading your commands sequentially by defining another way to read them. This is useful if you don’t want your instructions read in a strictly linear fashion. The main control structures in Perl are different types of if statements and loops.

If statements, as the naming implies, allow you to execute certain code if conditions are met. Related to if statements are elsif and else statements.

An if statement is structured as follows:

if ($condition==true){}#do stuff

If the logic inside () evaluates to true, the code inside {} will be executed. If not, the code will be skipped.

There are several ways to evaluate truth. The first is using the characters “==”. This checks if two statements are mathematically equivalent and if they are, return true. If not, it returns false. As usual, spacing is for readability and won’t change functionality as long as everything is in order.

if(1==1){}#1==1 is always true
if($ans==1){}#do stuff

Another way to evaluate truth is the “eq” operator. As opposed to checking to see if the statements are mathematically equivalent, this checks to see if each character in the variables are the same and in the same order.

if (“hi” eq “hi”){}#true
if(“1+1” eq “2”){}#false

The “else” operator can be used after an if-statement. This is useful so you don’t have to check something that’s redundant. For instance, if you want to edit a variable based on whether it is greater or less than 0, you will not have to check twice. Else is only called after an if-statement, creating one on its own will cause an error.

if ($number > 0 ){}# do some stuff
else {}#number <= 0

There is also the elsif operator. This is only called if the previous if statement or elsif statement is not true.

if ($myCar == “standard”){}#thats fine
elsif ($myCar == “fancy”){}#nice!
elsif ($myCar == “terrible”){}# I’m sad
else {}# I have no car

Loops

Loops are important if you want to do something a given number of times. They allow you to continue running commands until you want to stop running them. They do this by repeating the code contained inside the {} tags until the commands you set while making the loop tell it to stop.

For loops allow you to do something for a predetermined number of cycles. The number of cycles is set when the loop starts and can be set from a variable (here I use $num).

for ($i=0;$i<$num;$i++){}#do something using $i

A good example of using a loop would be to add elements from an array.

for ($i=0;$i<$arraylength-1;$i++){
$var += @array[i];}

A while loop allows you to continue to do something while the condition is true. If the condition never changes to false, you can end up with an infinite loop which will crash your program when it runs.

while (true){}#the code keeps running… forever

Because while loops are prone to crashing, it is best practice to only use them in situations where you don’t know how many times you need to run the loop.

while ($num != -1 && $num !=5){
$num = (($num-2)*2 % 10) - 1;}

A do-while loop is similar to a while loop, except that the do-while loop will always run at least once. Then, if the condition is true, the loop will run again. If the condition is false, the loop will end. Unlike for and while loops which check their conditions at the top of the loop, a do-while loop checks its condition at the bottom of a loop.

$a = 10;
do {
$a = $a + 1;
}while( $a < 20 ); #$a is equal to 20 at the end of the loop

Do-while loops may also be used to prevent division by zero. You can use a do-while loop to ensure that a randomly generated integer is not equal to 0.

do {
$e=&random(-5,5,1); #This creates a random integer between -5 and 5, including 0
}while($e == 0); #This loop will repeat until the random integer is not equal to 0

#This do-while loop ensures that the random integer can only be equal to -5 to -1 and 1 to 5

Or this:

Functions

What is a function? A function is a set of instructions. This is useful if you want to do something more than once in a problem or between problems, and makes your code easier to understand!

Functions allow you to use a single command to execute multiple lines of code. There are both user-defined functions and pre-defined functions. Pre-defined functions start with & then include the name of the function. Functions always have (), where arguments can be placed.

Random is a very commonly used function when creating randomly generated problems. In fact, it is by definition used in dynamic problems. To set a variable using random, set a variable to the random functions.

$variable = &random(0,10,1);

‘&random(a,b,c)’ is a function that gives a random number. The randomness of the number is determined by the numbers inside the, (), which are a,b, and c where these are variables that contain a number. A represents the minimum value of the random, b represents the maximum value, and c represents how big the difference is between the random numbers. For example &random(0,10,1) can return any integer between 0-10 {0,1,2,…,9,10} and &random(0,1,0.01) would return an number in the series {0,0.01,0.02,…0.98,0.99,1}.

There are many functions that are able to be used in a similar way. Click here for an exhaustive list of pre-defined functions.