SlideShare a Scribd company logo
1 of 44
Download to read offline
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
●   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 = "hellonworld!";
my $data = "08029t25";
my $data = "08029,"Eixample Esquerra"";
my $data = qq{08029,"Eixample Esquerra"};
Interpolación
my $hello = "Hola, $world!n";
my $hello = qq{Hola, "$world"!n};
Funciones tipicas de cadena
length EXPR
substr EXPR,OFFSET,LENGTH,REPLACEMENT
substr EXPR,OFFSET,LENGTH
substr EXPR,OFFSET
index STR,SUBSTR,POSITION
index 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
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
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 . " authorsn";
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 HASH
values HASH
print "Authors are ".keys(%name)."n";
Identificadores, variables y su
           notación
Notación
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 múltiples 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
 STDIN
STDOUT
STDERR
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     **
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)
right
left
left
not 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 LIST
   next if /^#/;
         ...
e.g.
print "Value is $valn" if $debug;
print $i++ while $i <= 10;
Contexto
* Void
find_chores();

* Lista
my @all_results = find_chores();
my ($single_element) = find_chores();
process_list_of_results( find_chores() );
my ($self,@args) = @_;

* Escalar
print "Hay ".@author." autoresn";
print "Hay ".scalar(@author)." autoresn";
# ++$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 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 context
my $stringy_x = '' . $x; # forces string context
my $boolean_x = !!$x; # forces boolean context
string context
my $boolean_x = !!$x; # forces boolean context
string context
my $boolean_x = !!$x; # forces boolean context

More Related Content

What's hot

Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix itRafael Dohms
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinosbrian d foy
 
循環参照のはなし
循環参照のはなし循環参照のはなし
循環参照のはなしMasahiro Honma
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Kris Wallsmith
 
Advanced modulinos trial
Advanced modulinos trialAdvanced modulinos trial
Advanced modulinos trialbrian d foy
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackVic Metcalfe
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPChad Gray
 
Climbing the Abstract Syntax Tree (php[world] 2019)
Climbing the Abstract Syntax Tree (php[world] 2019)Climbing the Abstract Syntax Tree (php[world] 2019)
Climbing the Abstract Syntax Tree (php[world] 2019)James Titcumb
 
Dip Your Toes in the Sea of Security (PHP South Africa 2017)
Dip Your Toes in the Sea of Security (PHP South Africa 2017)Dip Your Toes in the Sea of Security (PHP South Africa 2017)
Dip Your Toes in the Sea of Security (PHP South Africa 2017)James Titcumb
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHPTaras Kalapun
 
Climbing the Abstract Syntax Tree (PHP South Africa 2017)
Climbing the Abstract Syntax Tree (PHP South Africa 2017)Climbing the Abstract Syntax Tree (PHP South Africa 2017)
Climbing the Abstract Syntax Tree (PHP South Africa 2017)James Titcumb
 
London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)Dennis Knochenwefel
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
 
8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会Yusuke Ando
 
Climbing the Abstract Syntax Tree (PHP Developer Days Dresden 2018)
Climbing the Abstract Syntax Tree (PHP Developer Days Dresden 2018)Climbing the Abstract Syntax Tree (PHP Developer Days Dresden 2018)
Climbing the Abstract Syntax Tree (PHP Developer Days Dresden 2018)James Titcumb
 

What's hot (20)

Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
 
循環参照のはなし
循環参照のはなし循環参照のはなし
循環参照のはなし
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
Advanced modulinos trial
Advanced modulinos trialAdvanced modulinos trial
Advanced modulinos trial
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
 
My shell
My shellMy shell
My shell
 
PHP Tips & Tricks
PHP Tips & TricksPHP Tips & Tricks
PHP Tips & Tricks
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHP
 
wget.pl
wget.plwget.pl
wget.pl
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
Climbing the Abstract Syntax Tree (php[world] 2019)
Climbing the Abstract Syntax Tree (php[world] 2019)Climbing the Abstract Syntax Tree (php[world] 2019)
Climbing the Abstract Syntax Tree (php[world] 2019)
 
Dip Your Toes in the Sea of Security (PHP South Africa 2017)
Dip Your Toes in the Sea of Security (PHP South Africa 2017)Dip Your Toes in the Sea of Security (PHP South Africa 2017)
Dip Your Toes in the Sea of Security (PHP South Africa 2017)
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
 
Climbing the Abstract Syntax Tree (PHP South Africa 2017)
Climbing the Abstract Syntax Tree (PHP South Africa 2017)Climbing the Abstract Syntax Tree (PHP South Africa 2017)
Climbing the Abstract Syntax Tree (PHP South Africa 2017)
 
Codigos
CodigosCodigos
Codigos
 
London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)London XQuery Meetup: Querying the World (Web Scraping)
London XQuery Meetup: Querying the World (Web Scraping)
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
 
8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会
 
Climbing the Abstract Syntax Tree (PHP Developer Days Dresden 2018)
Climbing the Abstract Syntax Tree (PHP Developer Days Dresden 2018)Climbing the Abstract Syntax Tree (PHP Developer Days Dresden 2018)
Climbing the Abstract Syntax Tree (PHP Developer Days Dresden 2018)
 

Viewers also liked

6 August Daily technical trader
6 August Daily technical trader6 August Daily technical trader
6 August Daily technical traderQNB Group
 
Rozhovor o slobodě pro SLSP 1
Rozhovor o slobodě pro SLSP 1Rozhovor o slobodě pro SLSP 1
Rozhovor o slobodě pro SLSP 1Tomáš Hajzler
 
Punjab & maharashtra co op bank ltd recruitment of management trainee and tra...
Punjab & maharashtra co op bank ltd recruitment of management trainee and tra...Punjab & maharashtra co op bank ltd recruitment of management trainee and tra...
Punjab & maharashtra co op bank ltd recruitment of management trainee and tra...Tanay Kumar Das
 

Viewers also liked (7)

Sdo final
Sdo finalSdo final
Sdo final
 
6 August Daily technical trader
6 August Daily technical trader6 August Daily technical trader
6 August Daily technical trader
 
Gurt report 2009
Gurt report 2009Gurt report 2009
Gurt report 2009
 
El Growth09
El Growth09El Growth09
El Growth09
 
Tpl report may 2011
Tpl report may 2011Tpl report may 2011
Tpl report may 2011
 
Rozhovor o slobodě pro SLSP 1
Rozhovor o slobodě pro SLSP 1Rozhovor o slobodě pro SLSP 1
Rozhovor o slobodě pro SLSP 1
 
Punjab & maharashtra co op bank ltd recruitment of management trainee and tra...
Punjab & maharashtra co op bank ltd recruitment of management trainee and tra...Punjab & maharashtra co op bank ltd recruitment of management trainee and tra...
Punjab & maharashtra co op bank ltd recruitment of management trainee and tra...
 

Similar to Barcelona.pm Curs1211 sess01

Similar to Barcelona.pm Curs1211 sess01 (20)

Scripting3
Scripting3Scripting3
Scripting3
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
tutorial7
tutorial7tutorial7
tutorial7
 
tutorial7
tutorial7tutorial7
tutorial7
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011
 
Basic perl programming
Basic perl programmingBasic perl programming
Basic perl programming
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of Ruby
 

More from Javier Arturo Rodríguez

More from Javier Arturo Rodríguez (9)

Introduction to ansible
Introduction to ansibleIntroduction to ansible
Introduction to ansible
 
Minimizing cognitive load
 in Perl source code parsing (a.k.a. Pretty program...
Minimizing cognitive load
 in Perl source code parsing (a.k.a. Pretty program...Minimizing cognitive load
 in Perl source code parsing (a.k.a. Pretty program...
Minimizing cognitive load
 in Perl source code parsing (a.k.a. Pretty program...
 
WordPress Performance Tuning
WordPress Performance TuningWordPress Performance Tuning
WordPress Performance Tuning
 
WordPress for SysAdmins
WordPress for SysAdminsWordPress for SysAdmins
WordPress for SysAdmins
 
Easy native wrappers with SWIG
Easy native wrappers with SWIGEasy native wrappers with SWIG
Easy native wrappers with SWIG
 
Open Data: a view from the trenches
Open Data: a view from the trenchesOpen Data: a view from the trenches
Open Data: a view from the trenches
 
Build an autoversioning filesystem with Apache2
Build an autoversioning filesystem with Apache2Build an autoversioning filesystem with Apache2
Build an autoversioning filesystem with Apache2
 
Periodismo de Datos II: Construyendo y explorando conjuntos de datos con las ...
Periodismo de Datos II: Construyendo y explorando conjuntos de datos con las ...Periodismo de Datos II: Construyendo y explorando conjuntos de datos con las ...
Periodismo de Datos II: Construyendo y explorando conjuntos de datos con las ...
 
DatosEnCrudo.org
DatosEnCrudo.orgDatosEnCrudo.org
DatosEnCrudo.org
 

Recently uploaded

Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 

Recently uploaded (20)

Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 

Barcelona.pm Curs1211 sess01

  • 1. Barcelona Perl Mongers Curs de Perl 2012-11-10 Dades i Operadors
  • 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. * Before we start... $ perldoc #!/usr/bin/perl #!/usr/bin/env perl use strict;
  • 5. Datos Escalares ● Strings ● Numbers
  • 6. Strings Datos de texto o binarios, sin significado para el programa, delimitados tipicamente por comillas sencillas o dobles:
  • 7. Strings my $world = 'Mundo'; my $escaped = 'Dan O'Bannon'; my $backslash = '';
  • 8. Comillas dobles my $newline = "n"; my $tab = "t"; my $input = "hellonworld!"; my $data = "08029t25"; my $data = "08029,"Eixample Esquerra""; my $data = qq{08029,"Eixample Esquerra"};
  • 9. Interpolación my $hello = "Hola, $world!n"; my $hello = qq{Hola, "$world"!n};
  • 10. Funciones tipicas de cadena length EXPR substr EXPR,OFFSET,LENGTH,REPLACEMENT substr EXPR,OFFSET,LENGTH substr EXPR,OFFSET index STR,SUBSTR,POSITION index STR,SUBSTR
  • 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. 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. Hashes, Listas y Arreglos
  • 14. @ 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 . " authorsn"; my @num = (0..10); my @a = (@b,@c);
  • 15. # ++$learn $ perldoc List::Util
  • 16. % Hash my %name; $name{'Asimov'} = 'Isaac'; $name{'Bear'} = 'Greg'; $name{'King'} = 'Stephen';
  • 17. Funciones tipicas para hashes keys HASH values HASH print "Authors are ".keys(%name)."n";
  • 19. Notación 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);
  • 20. Para acceder el elemento de un arreglo o hash, se utiliza el sigil escalar: $nombre{$id} = 'Ann'; $nombre[$pos] = 'Ben';
  • 21. Es posible acceder múltiples valores al mismo tiempo utilizando el sigil de arreglo: @nombre{@keys} = @values; @suspendidos = @nombre[@selected]; @authors =("Asimov","Bear","King"); @authors = qw(Asimov Bear King);
  • 22. Variables especiales $ perldoc perlvar $ perldoc English @ARGV @INC %ENV %SIG $@ @_ $_
  • 23. I/O
  • 25. e.g. print STDERR "This is a debug messagen";
  • 26. Operadores y su precedencia ( y su asociatividad ( y su arity ( y su fixity ) ) )
  • 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 <><=>=ltgtlege nonassoc ==!=<=>eqnecmp~~ left & left |^ left && left || // nonassoc .. ... right ?: right =+= −= *= etc. left ,=> nonassoc list operators (rightward) right left left not and or xor
  • 28. => Atencion! print ( ($foo & 255) + 1, "n"); print ++$foo;
  • 29. * Operadores * Numericos * String * Logicos * Bitwise * Especiales
  • 30. * 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
  • 31. e.g. for(my $i=0; $i<@author; ++$i) { print $i.": ".$author[$i]."n"; }
  • 32. for(0..$#author) { print $_.": ".$author[$_]."n"; }
  • 33. foreach my $i (0..$#author) { print $i.": ".$author[$i]."n"; }
  • 34. for(0..1000000) { print $_,"n"; }
  • 35. while(<$fh>) { ... }
  • 36. * Modificadores if EXPR unless EXPR while EXPR until EXPR foreach LIST next if /^#/; ...
  • 37. e.g. print "Value is $valn" if $debug; print $i++ while $i <= 10;
  • 38. Contexto * Void find_chores(); * Lista my @all_results = find_chores(); my ($single_element) = find_chores(); process_list_of_results( find_chores() ); my ($self,@args) = @_; * Escalar print "Hay ".@author." autoresn"; print "Hay ".scalar(@author)." autoresn";
  • 39. # ++$learn $ perldoc -f wantarray
  • 40. * 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);
  • 41. * Cadena my $a = 2; print "The number is ".$a."n";
  • 42. * Booleano my $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 context my $stringy_x = '' . $x; # forces string context my $boolean_x = !!$x; # forces boolean context
  • 43. string context my $boolean_x = !!$x; # forces boolean context
  • 44. string context my $boolean_x = !!$x; # forces boolean context