Barcelona Perl Mongers     Curs de Perl       2012-11-10    Dades i Operadors
Dades I Operadors●   tipus bàsics: $scalar @array %hash●   cadenes de caràcters●   operadors numèrics i de cadenes●   cont...
* Before we start...      $ perldoc    #!/usr/bin/perl  #!/usr/bin/env perl      use strict;
Datos y Operadores
Datos Escalares●   Strings●   Numbers
StringsDatos de texto o binarios, sin significado para elprograma, delimitados tipicamente por comillas              senci...
Strings     my $world = Mundo;my $escaped = Dan OBannon;     my $backslash = ;
Comillas doblesmy $newline = "n";my $tab = "t";my $input = "hellonworld!";my $data = "08029t25";my $data = "08029,"Eixampl...
Interpolaciónmy $hello = "Hola, $world!n";my $hello = qq{Hola, "$world"!n};
Funciones tipicas de cadenalength EXPRsubstr EXPR,OFFSET,LENGTH,REPLACEMENTsubstr EXPR,OFFSET,LENGTHsubstr EXPR,OFFSETinde...
Functions for SCALARs or strings"chomp", "chop", "chr", "crypt", "hex", "index","lc",     "lcfirst","length", "oct", "ord"...
Números  perldoc perlnumber:$n = 1234; # decimal integer$n = 0b1110011; # binary integer$n = 01234; # *octal* integer$n =...
Hashes, Listas y Arreglos
@ Arreglomy @author;$author[0] = Asimov;$author[1] = Bear;$author[2] = King;print "First author is " . $author[0] . "n";pr...
# ++$learn$ perldoc List::Util
% Hashmy %name;$name{Asimov} = Isaac;$name{Bear} = Greg;$name{King} = Stephen;
Funciones tipicas para hasheskeys HASHvalues HASHprint "Authors are ".keys(%name)."n";
Identificadores, variables y su           notación
NotaciónLas variables son precedidas de un sigil que    indica el tipo de valor de la variable:                   $ Escal...
Para acceder el elemento de un arreglo o hash,          se utiliza el sigil escalar:            $nombre{$id} = Ann;       ...
Es posible acceder múltiples valores al mismotiempo utilizando el sigil de arreglo:@nombre{@keys} = @values;@suspendidos ...
Variables especiales$ perldoc perlvar$ perldoc English          @ARGV          @INC          %ENV          %SIG          $...
I/O
Consola STDINSTDOUTSTDERR
e.g.print STDERR "This is a debug messagen";
Operadores y su precedencia( y su asociatividad ( y su arity ( y su fixity ) ) )
$ perldoc perlop        left     terms and list operators (leftward)        left     −>        nonassoc ++ −−        right...
=> Atencion!print ( ($foo & 255) + 1, "n");          print ++$foo;
* Operadores * Numericos    * String   * Logicos   * Bitwise * Especiales
* Estructuras de Control                   if (EXPR) BLOCK            if (EXPR) BLOCK else BLOCKif (EXPR) BLOCK elsif (EXP...
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 LIST   next if /^#/;         ...
e.g.print "Value is $valn" if $debug;print $i++ while $i <= 10;
Contexto* Voidfind_chores();* Listamy @all_results = find_chores();my ($single_element) = find_chores();process_list_of_re...
# ++$learn$ perldoc -f wantarray
* Numericomy $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);
* Cadenamy $a = 2;print "The number is ".$a."n";
* Booleanomy $a = 0;print "a is truen" if $a;$a = 1;print "a is truen" if $a;$a = "a";print "a is truen" if $a;my $numeric...
string contextmy $boolean_x = !!$x; # forces boolean context
string contextmy $boolean_x = !!$x; # forces boolean context
Upcoming SlideShare
Loading in …5
×

Barcelona.pm Curs1211 sess01

562 views
463 views

Published on

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
562
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Barcelona.pm Curs1211 sess01

  1. 1. Barcelona Perl Mongers Curs de Perl 2012-11-10 Dades i Operadors
  2. 2. 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
  3. 3. * Before we start... $ perldoc #!/usr/bin/perl #!/usr/bin/env perl use strict;
  4. 4. Datos y Operadores
  5. 5. Datos Escalares● Strings● Numbers
  6. 6. StringsDatos de texto o binarios, sin significado para elprograma, delimitados tipicamente por comillas sencillas o dobles:
  7. 7. Strings my $world = Mundo;my $escaped = Dan OBannon; my $backslash = ;
  8. 8. Comillas doblesmy $newline = "n";my $tab = "t";my $input = "hellonworld!";my $data = "08029t25";my $data = "08029,"Eixample Esquerra"";my $data = qq{08029,"Eixample Esquerra"};
  9. 9. Interpolaciónmy $hello = "Hola, $world!n";my $hello = qq{Hola, "$world"!n};
  10. 10. Funciones tipicas de cadenalength EXPRsubstr EXPR,OFFSET,LENGTH,REPLACEMENTsubstr EXPR,OFFSET,LENGTHsubstr EXPR,OFFSETindex STR,SUBSTR,POSITIONindex STR,SUBSTR
  11. 11. 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
  12. 12. Números 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
  13. 13. Hashes, Listas y Arreglos
  14. 14. @ Arreglomy @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 . " authorsn";my @num = (0..10);my @a = (@b,@c);
  15. 15. # ++$learn$ perldoc List::Util
  16. 16. % Hashmy %name;$name{Asimov} = Isaac;$name{Bear} = Greg;$name{King} = Stephen;
  17. 17. Funciones tipicas para hasheskeys HASHvalues HASHprint "Authors are ".keys(%name)."n";
  18. 18. Identificadores, variables y su notación
  19. 19. NotaciónLas variables son precedidas de un sigil que indica el tipo de valor de la variable: $ Escalar @ Arreglo % Hash e.g. my($nombre, @nombre, %nombre);
  20. 20. Para acceder el elemento de un arreglo o hash, se utiliza el sigil escalar: $nombre{$id} = Ann; $nombre[$pos] = Ben;
  21. 21. Es posible acceder múltiples valores al mismotiempo utilizando el sigil de arreglo:@nombre{@keys} = @values;@suspendidos = @nombre[@selected];@authors =("Asimov","Bear","King");@authors = qw(Asimov Bear King);
  22. 22. Variables especiales$ perldoc perlvar$ perldoc English @ARGV @INC %ENV %SIG $@@_ $_
  23. 23. I/O
  24. 24. Consola STDINSTDOUTSTDERR
  25. 25. e.g.print STDERR "This is a debug messagen";
  26. 26. Operadores y su precedencia( y su asociatividad ( y su arity ( y su fixity ) ) )
  27. 27. $ 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 <><=>=ltgtlegenonassoc ==!=<=>eqnecmp~~ left & left |^ left && left || // nonassoc .. ...right ?: right =+= −= *= etc. left ,=> nonassoc list operators (rightward)rightleftleftnot and or xor
  28. 28. => Atencion!print ( ($foo & 255) + 1, "n"); print ++$foo;
  29. 29. * Operadores * Numericos * String * Logicos * Bitwise * Especiales
  30. 30. * Estructuras de Control if (EXPR) BLOCK if (EXPR) BLOCK else BLOCKif (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
  31. 31. e.g.for(my $i=0; $i<@author; ++$i) { print $i.": ".$author[$i]."n";}
  32. 32. for(0..$#author) { print $_.": ".$author[$_]."n";}
  33. 33. foreach my $i (0..$#author) { print $i.": ".$author[$i]."n";}
  34. 34. for(0..1000000) { print $_,"n";}
  35. 35. while(<$fh>) { ... }
  36. 36. * Modificadores if EXPR unless EXPR while EXPR until EXPR foreach LIST next if /^#/; ...
  37. 37. e.g.print "Value is $valn" if $debug;print $i++ while $i <= 10;
  38. 38. 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." autoresn";print "Hay ".scalar(@author)." autoresn";
  39. 39. # ++$learn$ perldoc -f wantarray
  40. 40. * Numericomy $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);
  41. 41. * Cadenamy $a = 2;print "The number is ".$a."n";
  42. 42. * Booleanomy $a = 0;print "a is truen" if $a;$a = 1;print "a is truen" if $a;$a = "a";print "a is truen" if $a;my $numeric_x = 0 + $x; # forces numeric contextmy $stringy_x = . $x; # forces string contextmy $boolean_x = !!$x; # forces boolean context
  43. 43. string contextmy $boolean_x = !!$x; # forces boolean context
  44. 44. string contextmy $boolean_x = !!$x; # forces boolean context

×