Tag Archives: variables

Lab02/3: first steps with Perl

This post is a part of the second laboratory session. Please refer to the main post. 

Ready to start programming? We hope so. This post will teach you the very first things 🙂

What a Perl program is

As we already said in class, a Perl program (or script, better), is a plain text file, as a FASTQ or SAM file is. It contains a set of instructions that the computer can execute. Unlike human beings, computers love repetitive tasks…

We are going to give you an actual lesson of Perl next Friday, but we think it is a good idea to make you touch it in advance.

Every programming language has:

  • variables: basically they are a piece of memory that can store an information, and has a name.
  • conditionals: we execute an instruction IF some condition is verified.
  • loops: we execute a set of instruction as many times as needed. Example: for every sequence in a FASTA file, calculate the reverse complement and print it.

Continue reading

Tagged , , ,

Perl variables

In any programming language we need to store information, an to retrieve it when needed. Perl has three types of variables:

  • scalar – they can store numbers or text (strings).
  • array – they are ordered lists of scalar.
  • hashes – they are unordered lists of values with a “label” called name.

Scalar are identified by the ‘$’ character. You can assign a value to a scalar with the ‘=’:

$age = 15;
$name = 'Larry';
$age = $age+1;        # an more compact alternative is $age++, if you have to add 1
$combine1 = "$name is $age";
$combine2 = '$name is $age';
print "Double quotes:  $combine1\n";
print "Sinngle quotes: $combine2\n;"

This small script has two assignation, a number and a string. Then we increment the $age variable by 1.
Note that for numbers we don’t use any quote, while for string we use single quotes or double quotes. The difference – as mentioned – is that double quotes are interpreted and substitute $name with the content of the variable itself.

Arrays are list of strings. To create a new array the syntax is a list of comma separated scalars enclosed by round brackets:

@array = ('first', 'second', 15, 16);

each element of the array has an index starting from 0, thus the last element of the array in the example has index 3. As each element of the array is a scalar, we refer to it with the “$” sign, specifying the index:

$firstElement = $array[0];

A special variable is created by Perl and contains the index of the last element:

$lastindex = $#array;

Thus:

$lastElement = $array[$#array];

Finally hashes are unordered lists of couples of scalar: one is the key and has an associated value.  We’ll see hashes in detail in lesson2.

(in Italian) c’è un buon tutorial su array ed hash in questo sito, valido anche per altri argomenti ovviamente… vi consiglio il corso completo come lettura serale ;).

Tagged , , , ,