SlideShare une entreprise Scribd logo
1  sur  5
Télécharger pour lire hors ligne
* 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

Contenu connexe

Tendances

Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
brian d foy
 

Tendances (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)
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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 ...
 

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

Dernier

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 

Dernier (20)

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 ...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
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
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
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
 
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
 
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
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

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