SlideShare uma empresa Scribd logo
1 de 44
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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)
 

Destaque

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
 

Destaque (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...
 

Semelhante a Barcelona.pm Curs1211 sess01

Semelhante a 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
 

Mais de Javier Arturo Rodríguez

Mais de 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
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Último (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

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