SlideShare ist ein Scribd-Unternehmen logo
1 von 5
Downloaden Sie, um offline zu lesen
* Before we start...



$ perldoc



#!/usr/bin/perl


use strict;




* Datos y Operadores

   * Datos Escalares

        * Strings

Datos de texto o binarios, sin significado para el programa, delimitados típicamente por comillas sencillas o dobles:

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 típicas 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///"

      => Más 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




                                                              1 de 5
@ 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);



                     * Funciones típicas para arreglos

         sort SUBNAME LIST
         sort BLOCK LIST
         sort LIST

         grep BLOCK LIST
         grep EXPR,LIST

         join EXPR,LIST

         split /PATTERN/,EXPR,LIMIT
         split /PATTERN/,EXPR
         split /PATTERN/

# ++$learn
$ perldoc List::Util



% Hash

          my %name;

          $name{'Asimov'} = 'Isaac';
          $name{'Bear'} = 'Greg';
          $name{'King'} = 'Stephen';

                     * Funciones típicas 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;




                                                          2 de 5
@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";

#!/usr/bin/perl
use strict;
use Chatbot::Eliza;

my $eliza = Chatbot::Eliza->new();
while(<STDIN>) {
        chomp;
        print "> ".$eliza->transform($_),"n";
}




           * Ficheros

$ perldoc -f open
$ perldoc perlopentut

           #
           # Reading from a file
           #

           # Please don't do this!
           open(FILE,"<$file");

           # Do *this* instead
           open my $fh, '<', 'filename' or die "Cannot read '$filename': $!n";
               while (<$fh>) {
                       chomp; say "Read a line '$_'";
               }


                  #
                  # Writing to a file
                  #

               use autodie;
               open my $out_fh, '>', 'output_file.txt';
               print $out_fh "Here's a line of textn";
               say     $out_fh "... and here's another";
           close $out_fh;

           # $fh->autoflush( 1 );




                                                       3 de 5
#
                   # There's much more!
                   # :mmap, :utf8, :crlf, ...
                   #

          open($fh, ">:utf8", "data.utf");
          print $fh $out;
          close($fh);

#   ++$learn
$   perldoc perlio
$   perldoc IO::Handle
$   perldoc IO::File


     * 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      < > <= >= lt gt le ge
             nonassoc      == != <=> eq ne cmp ~~
             left          &
             left          | ^
             left          &&
             left          || //
             nonassoc      .. ...
             right         ?:
             right         = += −= *= etc.
             left          , =>
             nonassoc      list operators (rightward)
             right         not
             left          and
             left          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";
                        }




                                                           4 de 5
for(0..$#author) {
                       print $_.": ".$author[$_]."n";
          }

                          foreach my $i (0..$#author) {
                          print $i.": ".$author[$i]."n";
                          }

                             for(0..1000000) {
                                     print $_,"n";
                             }

           while(<$fh>) {
                        # Skip comments
                        next if /^#/;
                        ...
           }

        * Modificadores

           if EXPR
           unless EXPR
           while EXPR
           until EXPR
           foreach LIST

           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




                                                             5 de 5

Weitere ähnliche Inhalte

Was ist angesagt?

Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
brian d foy
 

Was ist angesagt? (17)

Bag of tricks
Bag of tricksBag of tricks
Bag of tricks
 
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
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6
 
Parsing JSON with a single regex
Parsing JSON with a single regexParsing JSON with a single regex
Parsing JSON with a single regex
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
 
tutorial7
tutorial7tutorial7
tutorial7
 
Advanced modulinos trial
Advanced modulinos trialAdvanced modulinos trial
Advanced modulinos trial
 
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
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
Achieving Parsing Sanity In Erlang
Achieving Parsing Sanity In ErlangAchieving Parsing Sanity In Erlang
Achieving Parsing Sanity In Erlang
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
PHP object calisthenics
PHP object calisthenicsPHP object calisthenics
PHP object calisthenics
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 

Andere mochten auch

sport maakt jonger
sport maakt jongersport maakt jonger
sport maakt jonger
Joke
 
PresentacióN Informe Taller De Fotografia
PresentacióN Informe Taller De Fotografia PresentacióN Informe Taller De Fotografia
PresentacióN Informe Taller De Fotografia
Leonel Vasquez
 
Cascao Hydropolitics TWM Lake Victoria 2009 (II)
Cascao Hydropolitics TWM Lake Victoria 2009 (II)Cascao Hydropolitics TWM Lake Victoria 2009 (II)
Cascao Hydropolitics TWM Lake Victoria 2009 (II)
Ana Cascao
 
Indonesian Photos 07
Indonesian Photos   07Indonesian Photos   07
Indonesian Photos 07
sutrisno2629
 
Land 'Grabbing' in the Nile Basin and implications for the regional water sec...
Land 'Grabbing' in the Nile Basin and implications for the regional water sec...Land 'Grabbing' in the Nile Basin and implications for the regional water sec...
Land 'Grabbing' in the Nile Basin and implications for the regional water sec...
Ana Cascao
 
Cascao Leipzig Waterscapes Nile Basin
Cascao Leipzig Waterscapes Nile BasinCascao Leipzig Waterscapes Nile Basin
Cascao Leipzig Waterscapes Nile Basin
Ana Cascao
 
A Touching Story4007
A Touching Story4007A Touching Story4007
A Touching Story4007
sutrisno2629
 
Programació orientada a objectes en Perl
Programació orientada a objectes en PerlProgramació orientada a objectes en Perl
Programació orientada a objectes en Perl
Alex Muntada Duran
 
Benvinguda al Curs d'introducció a Perl 2011
Benvinguda al Curs d'introducció a Perl 2011Benvinguda al Curs d'introducció a Perl 2011
Benvinguda al Curs d'introducció a Perl 2011
Alex Muntada Duran
 

Andere mochten auch (20)

Real Value in Real Time: MongoDB-based Analytics at TeachStreet
Real Value in Real Time: MongoDB-based Analytics at TeachStreetReal Value in Real Time: MongoDB-based Analytics at TeachStreet
Real Value in Real Time: MongoDB-based Analytics at TeachStreet
 
sport maakt jonger
sport maakt jongersport maakt jonger
sport maakt jonger
 
Kansberekening
KansberekeningKansberekening
Kansberekening
 
Instructional Design for the Semantic Web
Instructional Design for the Semantic WebInstructional Design for the Semantic Web
Instructional Design for the Semantic Web
 
Evolving a strategy for Emerging and startup companies
Evolving a strategy for Emerging and startup companiesEvolving a strategy for Emerging and startup companies
Evolving a strategy for Emerging and startup companies
 
PresentacióN Informe Taller De Fotografia
PresentacióN Informe Taller De Fotografia PresentacióN Informe Taller De Fotografia
PresentacióN Informe Taller De Fotografia
 
From idea to exit
From idea to exitFrom idea to exit
From idea to exit
 
Cascao Hydropolitics TWM Lake Victoria 2009 (II)
Cascao Hydropolitics TWM Lake Victoria 2009 (II)Cascao Hydropolitics TWM Lake Victoria 2009 (II)
Cascao Hydropolitics TWM Lake Victoria 2009 (II)
 
Notetaking
NotetakingNotetaking
Notetaking
 
Frases Célebres
Frases CélebresFrases Célebres
Frases Célebres
 
Indonesian Photos 07
Indonesian Photos   07Indonesian Photos   07
Indonesian Photos 07
 
Land 'Grabbing' in the Nile Basin and implications for the regional water sec...
Land 'Grabbing' in the Nile Basin and implications for the regional water sec...Land 'Grabbing' in the Nile Basin and implications for the regional water sec...
Land 'Grabbing' in the Nile Basin and implications for the regional water sec...
 
Cascao Leipzig Waterscapes Nile Basin
Cascao Leipzig Waterscapes Nile BasinCascao Leipzig Waterscapes Nile Basin
Cascao Leipzig Waterscapes Nile Basin
 
A Touching Story4007
A Touching Story4007A Touching Story4007
A Touching Story4007
 
030413
030413030413
030413
 
Las vanguardias históricas
Las vanguardias históricasLas vanguardias históricas
Las vanguardias históricas
 
From Idea to Exit, the story of our startup
From Idea to Exit, the story of our startupFrom Idea to Exit, the story of our startup
From Idea to Exit, the story of our startup
 
Programació orientada a objectes en Perl
Programació orientada a objectes en PerlProgramació orientada a objectes en Perl
Programació orientada a objectes en Perl
 
Benvinguda al Curs d'introducció a Perl 2011
Benvinguda al Curs d'introducció a Perl 2011Benvinguda al Curs d'introducció a Perl 2011
Benvinguda al Curs d'introducció a Perl 2011
 
Erik Scarcia
Erik Scarcia Erik Scarcia
Erik Scarcia
 

Ähnlich wie Dades i operadors

Scripting3
Scripting3Scripting3
Scripting3
Nao Dara
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
rhshriva
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 

Ähnlich wie Dades i operadors (20)

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
 
Scripting3
Scripting3Scripting3
Scripting3
 
Subroutines
SubroutinesSubroutines
Subroutines
 
tutorial7
tutorial7tutorial7
tutorial7
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Bouncingballs sh
Bouncingballs shBouncingballs sh
Bouncingballs sh
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
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)
 
Maybe you do not know that ...
Maybe you do not know that ...Maybe you do not know that ...
Maybe you do not know that ...
 

Mehr von Alex Muntada Duran (9)

Equips cibernètics, realitat o ficció? (Jornada TIC UPC 2017)
Equips cibernètics, realitat o ficció? (Jornada TIC UPC 2017)Equips cibernètics, realitat o ficció? (Jornada TIC UPC 2017)
Equips cibernètics, realitat o ficció? (Jornada TIC UPC 2017)
 
Desenvolupament al projecte Debian
Desenvolupament al projecte DebianDesenvolupament al projecte Debian
Desenvolupament al projecte Debian
 
REST in theory
REST in theoryREST in theory
REST in theory
 
Comiat del curs de Perl
Comiat del curs de PerlComiat del curs de Perl
Comiat del curs de Perl
 
Benvinguda al curs de Perl
Benvinguda al curs de PerlBenvinguda al curs de Perl
Benvinguda al curs de Perl
 
Orientació a objectes amb Moose
Orientació a objectes amb MooseOrientació a objectes amb Moose
Orientació a objectes amb Moose
 
Cloenda del Curs d'introducció a Perl 2011
Cloenda del Curs d'introducció a Perl 2011Cloenda del Curs d'introducció a Perl 2011
Cloenda del Curs d'introducció a Perl 2011
 
Modern Perl Toolchain
Modern Perl ToolchainModern Perl Toolchain
Modern Perl Toolchain
 
dh-make-perl
dh-make-perldh-make-perl
dh-make-perl
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Kürzlich hochgeladen (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 

Dades i operadors

  • 1. * Before we start... $ perldoc #!/usr/bin/perl use strict; * Datos y Operadores * Datos Escalares * Strings Datos de texto o binarios, sin significado para el programa, delimitados típicamente por comillas sencillas o dobles: 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 típicas 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///" => Más 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 1 de 5
  • 2. @ 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); * Funciones típicas para arreglos sort SUBNAME LIST sort BLOCK LIST sort LIST grep BLOCK LIST grep EXPR,LIST join EXPR,LIST split /PATTERN/,EXPR,LIMIT split /PATTERN/,EXPR split /PATTERN/ # ++$learn $ perldoc List::Util % Hash my %name; $name{'Asimov'} = 'Isaac'; $name{'Bear'} = 'Greg'; $name{'King'} = 'Stephen'; * Funciones típicas 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; 2 de 5
  • 3. @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"; #!/usr/bin/perl use strict; use Chatbot::Eliza; my $eliza = Chatbot::Eliza->new(); while(<STDIN>) { chomp; print "> ".$eliza->transform($_),"n"; } * Ficheros $ perldoc -f open $ perldoc perlopentut # # Reading from a file # # Please don't do this! open(FILE,"<$file"); # Do *this* instead open my $fh, '<', 'filename' or die "Cannot read '$filename': $!n"; while (<$fh>) { chomp; say "Read a line '$_'"; } # # Writing to a file # use autodie; open my $out_fh, '>', 'output_file.txt'; print $out_fh "Here's a line of textn"; say $out_fh "... and here's another"; close $out_fh; # $fh->autoflush( 1 ); 3 de 5
  • 4. # # There's much more! # :mmap, :utf8, :crlf, ... # open($fh, ">:utf8", "data.utf"); print $fh $out; close($fh); # ++$learn $ perldoc perlio $ perldoc IO::Handle $ perldoc IO::File * 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 < > <= >= lt gt le ge nonassoc == != <=> eq ne cmp ~~ left & left | ^ left && left || // nonassoc .. ... right ?: right = += −= *= etc. left , => nonassoc list operators (rightward) right not left and left 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"; } 4 de 5
  • 5. for(0..$#author) { print $_.": ".$author[$_]."n"; } foreach my $i (0..$#author) { print $i.": ".$author[$i]."n"; } for(0..1000000) { print $_,"n"; } while(<$fh>) { # Skip comments next if /^#/; ... } * Modificadores if EXPR unless EXPR while EXPR until EXPR foreach LIST 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 5 de 5