Saltar a contenido

Introduction to Perl

eFlow was developed during the years 1998 and 2002. During these years Perl was a popular language for the development of Web applications, it has several benefits:

  • It is very easy to learn
  • It is a scripting language with a fairly fast execution level
  • It is unstructured, does not require variable declarations and all data types are "variant".

Although eFlow allows the use of other languages to create pop-up windows that allow eFlow to interact with other systems. Perl is the only language with which pre- and post-processes can be programmed.

This is the main reason why we must learn Perl to be able to exploit the capabilities of eFlow to the fullest.

This brief introduction aims to help a programmer who is not familiar with the language to acquire the basic knowledge that will allow him to read the eFlow code, create and modify post-processes and pre-processes, within the eFlow development environment.

Variables

It is not necessary to declare variables before using them. If a variable is not declared as explicitly local is considered global. Perl only handles the following data types: integers, decimal numbers, text strings, and pointers. And these data types can be organized within the following structures: scalar variables, arrays and hashes.

Scalars

Similar to "Variant" type variables in other languages. Scalar variables are declared with the weight sign and then the name.

$name = "Juan Perez";
$age = 25;
$height = 1.80;
$a = 1;
$a = 'string';

As can be seen in the examples, there was no need to declare the type of data that we want to store in the variable, we have simply assigned it. We can also see that in the case of the variable $a, we assign it an integer value and later a text string value. This is legal the variable is not tied to any specific value type.

Single and double quotes

To assign string values we can use single or double quotes. Each one has a special meaning when making the assignment.

Single quotes

The string is literal as it looks written. That is, the values are assigned exactly as they appear within the single quotes, there is no interpretation of the data, substitution of values, etc.

Double quotation marks

The string is interpreted and the internal values are evaluated to form the final string.

Example:

For the following values

@midominio = (1,2,3,4);
$nombre = 'Juan';
$app = 'Perez';
$apm = 'Lopez';
Expression Result
'The email address is account@mydomain.com' The email address is account@mydomain.com
'The total amount is $40,000 pesos' The total amount is $40,000 pesos
"The email address is account@mydomain.com" The email address is account1234.com
"The total amount is $40,000 pesos" The total amount is 40,000 pesos
"My name is $name $app $apm" My name is Juan Perez Lopez
"The total amount is $40,000 pesos" The total amount is $40,000 pesos

Arrays

Arrays are a collection of elements that do not necessarily have to be of the same type, that is, within an array-type variable an indeterminate number of elements can be stored. elements, which can be string, integer, decimal, another variable, a pointer, etc. Unlike other languages, the length of the array does not need to be declared; it grows or shrinks dynamically as the array is manipulated.

Arrays are declared using the @ symbol. And to access its elements, the "$" sign and the square brackets are used to indicate the position in the array "[index]", indicating that we want to access an element as if it were a scalar. All arrays start with index 0

Examples

$app = 'Perez';
$apm = 'Lopez';
@numeros = (1,2,3,4);
@revuelto = ('Nombre',23,$app,&$apm,3.1416);
$#@numeros; #esto es igual el último índice del arreglo.

$numeros[1]; # Valor 2
$numeros[$#numeros]; # Valor 4
$revuelto[2] = # Valor Perez

Hash

Structures of this type are an array where the indexes can be numbers or letters. They are handled in the same way as arrangements. To declare them we use the percentage symbol "%To access an index we use the "$" sign and the curly braces "{index}", to indicate the position.

$app = 'Perez';
$indice = 'apellido';
%numeros = (
    'uno',1,
    'dos',2,
    'tres'3,
    'cuatro',4
);
%persona = (
    'nombre','Juan',
    'edad',23,
    'apellido',$app,
    'pi',3.1416
);

$numeros{'dos'}; # Valor 2
$persona{'edad'}; # valor 23
$persona{$apellido}; # Valor 'Perez'

Flow control

if

if (condicion) {

} elsif (condicion) {

} else {

}

Careful

Since But it does not have data types, it is necessary to indicate what type of comparison we want to make between two variables. A string comparison, or a numerical comparison.

Comparison Numeric Strings
Same == eq
Different != ne
Greater than > gt
Less than < lt
Greater than or equal to >= ge
Less than or equal to <= le

And = &&
Or = ||

for

The structure of a for is as follows:

for (init; compare; modify) {
}

Donde:

part meaning
init assign initial value to control variable
compare condition that must be met to carry out the cycle
modify modify control variable
for ($i=5; $i < 10; $i++) {
    print "I = $i\n";
}
for ($i=10; $i > 5; $i--) {
    print "I = $i\n";
}
for ($a = '123456'; length($a)>0; $char = chop($a)) {
    print "$char\n";
}

while

The structure of a while is as follows:

while (comparación) {
    # código
}

until

do {
    # código
} until (comparación);

foreach

The foreach iterates over the values of an array or list in sequential order, removing the first element of the list each time until the array has no more elements. This action does not modify the original arrangement.

foreach $variable (@arreglo) {
    print "$variable\n";
}

# Ejemplo:

@nombres(diana,david,Juan,miguel,humberto);
foreach $nombre (@nombres){
    print "Nombre = $nombre\n";
}

Predefined functions

chop

Removes the last character from the string (this shortens one character), and returns the extracted character.

$a = 'abcdef';
$c = chop($a);
print "$a\núltimo caracter:$c\n";

uc, lc, ucfirst, lcfirst

function action
uc Converts lowercase letters to uppercase.
lc Converts uppercase letters to lowercase.
ucfirst Converts the first letter to uppercase.
lcfirst Converts the first letter to lowercase.

join

The join function is used to join elements in a list using a symbol.

join exp,lista;
# exp = Carácter que unirá los elementos.
# lista = Lista que va a unir.

@palabras = ('uno','dos','tres',123,456,789);
$concatenado = join '|',@palabras;
print "Concatenado = $concatenado\n"; # Concatenado = uno|dos|tres|123|456|789

split

This function separates elements, which it passes to an array, it can be applied to both arrays and variables.

split /regex/,variable;

# separator: It is the character where the element ends
# variable: It is what is going to be separated

$linea = "Hans,Peyrot,39,1.86,Veracruz";
@v = split /,/,$linea; # Valores se localizan en $v[0],$v[1], ...
($nom,$ap,$edad,$est,$cd) = split /,/,$linea; # Valores asignados directamente a cada variable

eval

The eval function has 2 main uses.

  1. interprets a string of Perl expressions and executes them.
  2. Execute a portion of code without stopping if there are execution errors. Allows you to control errors in modules, objects, etc.
$formula = '$v = $d / $t';
$d = 100;
$t = 2;
eval $formula;
print "$v\n"; # $v = 50

$b = 0;
eval {
    $v = $d / $b;
};
if ($@) {
    print "Error de ejecución: $@";
    exit 0;
}

Subroutines and Functions

In Perl, all subroutines return a value, this value can be explicit if the "return" statement is used. Or implicit, when a value is not returned with return, the value returned by the last statement within the subroutine.

$numero_1 = 10;
$numero_2 = 982;
$mensaje = "Ejemplo 1 de subrutinas";
print "$mensaje \n";
$res = suma();
print "Resultado = $res";
# Subrutina
sub suma{
    my $r;

    $r = $numero_1 + numero_2;
    return $r;
}

# Subroutine Example 2
$info ="Juan-25-11/11/1978-Mexico,D.F.";
separa();
# Subrutina
sub separa{
    @valores = split /-/,$linea;
    foreach $info (@valores){
        print "$info";
    }
}

Global and Local Variables

In Perl there are global and local variables. Global ones are those that can be used anywhere in the program, local ones, on the other hand, are used in blocks of code, such as functions or subroutines. When declaring any variable it is created as a global variable, unless let's prepend the reserved word my before the declaration of the variable, in this case the variable becomes local within the block in which it is declared.

# Declaration of a global variable
$var;
# Local variable declaration
my $var;

$global = "Global";
print "Esta es una variable global : $global\n";
local();

sub local{
    my $global="Local";
    print "Esta es una variable local : $global\n";
}

Parameters to subroutines

Parameters to perl subroutines are always by value. If we want to send a value by reference we must send a pointer to our variable.

$a = "Valor especial";
rutina($a)
rutina2($a,'otro valor',\$a); # \ : pasar el apuntador a la variable, no el valor
rutina3($a,'otro valor',\$a);

sub rutina {
    my $variable = shift;
    print "Mi parámetro es : $variable\n";
}

sub rutina2 {
    my ($v1,$v2,$apuntador) = @_;
    # valores en $v1,$v2 y $apuntador
}

sub rutina3 {
    my @v = @_;
    # valores en $v[0], $v[1], $v[2]
}

Regular expressions

Regular expressions are patterns that are searched for within a text, as a pattern we understand a certain combination of characters.

Find and replace

=~ s/pattern searched/replacement/gi;

element meaning
searched pattern What you are looking for
replacement So the pattern will be replaced
g Find all occurrences (optional)
i Ignore capitalization (optional)

Find

=~ /pattern/gi;

element meaning
pattern What you are looking for
g Find all occurrences (optional)
i Ignore capitalization (optional)

Special symbols on patterns

Symbol meaning
. Any character
\ Metacharacter, escape next character, do not interpret any meaning
^ Find the pattern at the beginning of the string
$ Find pattern at end of string
| Toggle between two values around the bar
() Group a pattern
[] Create a character class to search for

MODIFIERS

Symbol meaning
+ One or more times
* Zero or more times
? Zero or once

PREDEFINED

Symbol meaning
\d Digit
\D No digit
\w Word character a-z,0-9 and _
\W No letter of words
\s Blank character
\S No blank character

ACCESS TO FILES

The instruction to open a file is: open(Descriptor,"option[:encoding]"","path to file");

Element Meaning
Descriptor File reference, examples: $fh , MEMO
Path to file Path where the file is located on the system
option How you want to open the file.
< Reading
> Write (delete file if it exists)
<+ Reading and writing
>+ Write and read (deletes file if it exists)
>> Append
encoding What encoding do we want to use to read or write
Omitted ISO-8859-1 (Latin1)
utf8 Encode or decode UTF8
if (open(MEMO,"<:utf8","memo.txt")) {
    print "Archivo memo.txt abierto para lectura\nDecodificando UTF8\n";
    print "Contenido del archivo\n";
    while ($linea = <MEMO>) {
        print "Línea leida : $linea\n"
    }
} else {
    print "Error al abrir memo.txt";
    exit 0;
}

Libraries and objects

Perl allows you to load libraries or object packages that allow us to extend the use of the language. There are many libraries for different functions, such as:

  • Date manipulation
  • Connections to servers: HTTP, HTTPS, FTP, SSH, REST services, WebService, etc.
  • Process documents: PDF, Excel, CSV
  • Database clients: Postgresq1, MSSQL, MySQL, sqlite, Oracle, etc.

The bookstores are located at the following address:

metacpan.org

  • Search by functionality, name, etc.
  • Each available library has documentation on how it is used

To be able to install a new library. As root user, in a bash session

cpanm -iqn Clase::Libreria

To load and use a library.

use DBI;

$dbh = DBI->connect("dsn a base de datos") or die "DBI::errstr";
$sth = $dbh->prepare("select * from tabla") or die "DBI::errstr";
$sth->execute() or die "DBI::errstr";
while ($rs = $sth->fetchrow_hashref) {
    print "Valor de tabla: $$rs{'columna'}\n";

}

References

Sites on the Internet

Perl official site, http://www.perl.org

Perl documentation, http://www.perldoc.com

Perl Tutorials, http://flanagan.ugr.es/perl/

Books

Perl, Manual de Referencia
Martín C. Brown
McGraw-Hill