barcelona.pm curs1211 sess01
DESCRIPTION
TRANSCRIPT
Barcelona Perl Mongers
Curs de Perl2012-11-10
Dades i Operadors
Dades I Operadors
● tipus bàsics: $scalar @array %hash● cadenes de caràcters● operadors numèrics i de cadenes● control del flux: condicionals, bucles i errors● entrada/sortida: STDIN STDOUT
* Before we start...
$ perldoc
#!/usr/bin/perl#!/usr/bin/env perl
use strict;
Datos y Operadores
Datos Escalares
● Strings● Numbers
Strings
Datos de texto o binarios, sin significado para el programa, delimitados tipicamente por comillas
sencillas o dobles:
Strings
my $world = 'Mundo';my $escaped = 'Dan O\'Bannon';
my $backslash = '\\';
Comillas dobles
my $newline = "\n";my $tab = "\t";my $input = "hello\nworld!";my $data = "08029\t25";my $data = "08029,\"Eixample Esquerra\"";my $data = qq{08029,"Eixample Esquerra"};
Interpolacion
my $hello = "Hola, $world!\n";my $hello = qq{Hola, "$world"!\n};
Funciones tipicas de cadena
length EXPRsubstr EXPR,OFFSET,LENGTH,REPLACEMENTsubstr EXPR,OFFSET,LENGTHsubstr EXPR,OFFSETindex STR,SUBSTR,POSITIONindex STR,SUBSTR
Functions for SCALARs or strings
"chomp", "chop", "chr", "crypt", "hex", "index","lc", "lcfirst","length", "oct", "ord", "pack", "q//",
"qq//","reverse", "rindex","sprintf", "substr", "tr///", "uc", "ucfirst", "y///"
=> Mas cuando hablemos de expresiones regulares
Numeros
perldoc perlnumber:
$n = 1234; # decimal integer
$n = 0b1110011; # binary integer
$n = 01234; # *octal* integer
$n = 0x1234; # hexadecimal integer
$n = 12.34e−56; # exponential notation
$n = "−12.34e56"; # number specified as a string
$n = "1234"; # number specified as a string
Hashes, Listas y Arreglos
@ Arreglo
my @author; $author[0] = 'Asimov';$author[1] = 'Bear';$author[2] = 'King';print "First author is " . $author[0] . "\n";print "Last author is " . $author[$#author] . "\n";print "Last author is " . $author[-1] . "\n";print "There are " . @author . " authors\n";my @num = (0..10);my @a = (@b,@c);
# ++$learn
$ perldoc List::Util
% Hash
my %name; $name{'Asimov'} = 'Isaac'; $name{'Bear'} = 'Greg'; $name{'King'} = 'Stephen';
Funciones tipicas para hashes
keys HASHvalues HASH print "Authors are ".keys(%name)."\n";
Identificadores, variables y su notacion
Notacion
Las variables son precedidas de un sigil que indica el tipo de valor de la variable:
$ Escalar@ Arreglo% Hash
e.g.my($nombre, @nombre, %nombre);
Para acceder el elemento de un arreglo o hash, se utiliza el sigil escalar:
$nombre{$id} = 'Ann';$nombre[$pos] = 'Ben';
Es posible acceder multiples valores al mismo tiempo utilizando el sigil de arreglo:@nombre{@keys} = @values;@suspendidos = @nombre[@selected];@authors =("Asimov","Bear","King");@authors = qw(Asimov Bear King);
Variables especiales
$ perldoc perlvar$ perldoc English @ARGV @INC %ENV %SIG $@@_ $_
I/O
Consola
STDINSTDOUTSTDERR
e.g.
print STDERR "This is a debug message\n";
Operadores y su precedencia
( y su asociatividad ( y su arity ( y su fixity ) ) )
$ perldoc perlop left terms and list operators (leftward) left −> nonassoc ++ −− right **right !~\ and unary + and − left =~ !~ left */%x left +−. left << >> nonassoc named unary operators nonassoc <><=>=ltgtlege nonassoc ==!=<=>eqnecmp~~ left & left |^ left && left || // nonassoc .. ... right ?: right =+= −= *= etc. left ,=> nonassoc list operators (rightward) rightleftleftnot and or xor
=> Atencion!
print ( ($foo & 255) + 1, "\n"); print ++$foo;
* Operadores
* Numericos* String
* Logicos* Bitwise
* Especiales
* Estructuras de Control
if (EXPR) BLOCK if (EXPR) BLOCK else BLOCK
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK LABEL while (EXPR) BLOCK
LABEL while (EXPR) BLOCK continue BLOCK LABEL until (EXPR) BLOCK
LABEL until (EXPR) BLOCK continue BLOCK LABEL for (EXPR; EXPR; EXPR) BLOCK
LABEL foreach VAR (LIST) BLOCK LABEL foreach VAR (LIST) BLOCK continue BLOCK
LABEL BLOCK continue BLOCK
e.g.
for(my $i=0; $i<@author; ++$i) { print $i.": ".$author[$i]."\n";}
for(0..$#author) { print $_.": ".$author[$_]."\n";}
foreach my $i (0..$#author) { print $i.": ".$author[$i]."\n";}
for(0..1000000) { print $_,"\n";}
while(<$fh>) { ... }
* Modificadores
if EXPR unless EXPR while EXPR until EXPR
foreach LISTnext if /^#/;
...
e.g.
print "Value is $val\n" if $debug; print $i++ while $i <= 10;
Contexto
* Voidfind_chores();
* Listamy @all_results = find_chores();my ($single_element) = find_chores();process_list_of_results( find_chores() );my ($self,@args) = @_;
* Escalarprint "Hay ".@author." autores\n";print "Hay ".scalar(@author)." autores\n";
# ++$learn
$ perldoc -f wantarray
* Numerico
my $a = "a";my $b = "b";print "a is equal to b " if ($a==$b); # Really?print "a is equal to b " if ($a eq $b);
* Cadena
my $a = 2;print "The number is ".$a."\n";
* Booleano
my $a = 0;print "a is true\n" if $a;$a = 1;print "a is true\n" if $a;$a = "a";print "a is true\n" if $a;my $numeric_x = 0 + $x; # forces numeric contextmy $stringy_x = '' . $x; # forces string contextmy $boolean_x = !!$x; # forces boolean context
string context
my $boolean_x = !!$x; # forces boolean context
string context
my $boolean_x = !!$x; # forces boolean context