SlideShare una empresa de Scribd logo
1 de 137
Perl Welcome Pratical Extraction and Reporting Language Marcos Rebelo oleber@gmail.com
Perl - Larry Wall ,[object Object]
Quotes: ,[object Object]
There's More Than One Way to Do It
What is Perl? ,[object Object]
Supports both procedural and OO programming.
It has powerful built-in support for text processing
It has one of the world's most impressive collections of third-party modules (http://www.cpan.org).
Perl – Pros ,[object Object]
Open Source, and free licencing
Excellent text handling and regular expressions
Large experienced active user base
Fast, for an interpreted language
Code developed is generally cross plaform
Very easy to write powerful programs in a few lines of code
Perl – Cons ,[object Object]
Can look complicated, initially, particularly if you're not familiar with regular expressions
Consider using for ,[object Object]
System administration
Most command line applications
Batch processing
Reports
Database access and manipulation
Any application involving significant text processing
Hello World ,[object Object]
Basic syntax overview ,[object Object]
You can use parentheses for subroutines arguments or omit them according to your personal taste.  say "Hello, world!";
Comments start with a  #  and run to the end of the line. # This is a comment
Basic syntax overview ,[object Object]
However, only double quotes interpolate variables and special characters such as newlines (
): print("Hello,  $name!
 ");    # interpolate $name print('Hello,  $name!
 ');    # prints $name!
 literally
Basic syntax overview ,[object Object]
... except inside quoted strings: print("Hello    world");   # this would print with a   # line break in the middle.
Use feature qw(say) ,[object Object],Is equivalent to: ,[object Object],We will see later that the correct expression is: ,[object Object]
Running Perl programs ,[object Object]
Alternatively, put this shebang in your script : #!/usr/bin/perl and run your executable script #> progname.pl
-e : allows you to define the Perl code in the command line to be executed, -E to get 5.10  #> perl -e 'print("Hello, World!
")'
Perl variable types ,[object Object]
Arrays my  @ animals = ('camel', 'lama'); my  @ numbers = (23, 42, 69); my  @ mixed = ('camel', 42, 1.23);
Associative Array / Hash Tables my  % fruit_color = (   apple  => 'red',   banana => 'yellow' );
Scalar Type ,[object Object]
my  $ answer  = 42;
my  $ scalar_ref = $scalar; ,[object Object],[object Object]
Array Type ,[object Object]
my  @ numbers = (23, 42, 69);
my  @ mixed = ('camel', 42, 1.23); ,[object Object],[object Object]
print( $ numbers [-1] ); # prints 69
Array Slice ,[object Object]
@ numbers [0..2] ; # gives (23, 42, 69);
@ numbers [1..$#numbers] ;  ,[object Object]
@ numbers [2, 1]  =  @ numbers [1, 2] ;
($scalar1, $scalar2) = @numbers;
Array Type ,[object Object]
if ( scalar( @animals )  < 5) { ... }
Associative Array Type Hash table ,[object Object]
Associative Array Type Hash table ,[object Object]
$ fruit_color{banana};  # &quot;yellow&quot; ,[object Object],[object Object]
my @colors =  values (%fruit_colors); ,[object Object]
Hash Slice ,[object Object]
Variable Reference ,[object Object]
Complex data types ,[object Object]
my @citiesPT =  @{ $cities->{PT} } ;
Lexical Variables ,[object Object],However, the above usage will create global variables throughout your program.  ,[object Object]
Lexical Variables ,[object Object]
Lexical Variables ,[object Object]
Magic variables ,[object Object]
@ARGV : the command line arguments to your script.
$ARGV : contains the name of the current file when reading from  <>  or  readline() .
@_ : the arguments passed to a subroutine.
$a ,  $b : Special package variables when using  sort() .
$/ : The input record separator, newline by default.
Most common operators ,[object Object]
-  -=  subtraction
*  *=  multiplication
/  /=  division ,[object Object],[object Object]
||  or
!  not
Most common operators ,[object Object]
.   string concatenation
x   string multiplication
..  range operator (creates a list of numbers)
Most common operators
Conditional constructs ,[object Object]
if  COND BLOCK  else  BLOCK
if  COND BLOCK  elsif  COND BLOCK
if  COND BLOCK  elsif  COND BLOCK  else  BLOCK ,[object Object],[object Object]
Conditional constructs ,[object Object]
This is provided as a 'more readable' version of  if  (  not(  is_valid( $value )   )  ) {    ...  }
0, '0', '', () and undef are all false in a boolean context. All other values are true.
Conditional constructs ,[object Object]
The Perlish post-condition way print(&quot;Yow!&quot;)  if $zippy; print(&quot;No cubes&quot;)  unless $cubes;
while looping constructs ,[object Object]
There's also a negated version (don't use it): until   ( is_valid( $value ) ) { … }
You can also use while in a post-condition: print(&quot;xpto
&quot;)  while  condition;
Going throw a hash: while  (my ($key,$value) =  each (%ENV)){   print &quot;$key=$value
&quot;; }
for looping constructs ,[object Object],The C style for loop is rarely needed in Perl since Perl provides the more friendly foreach loop. ,[object Object]
foreach looping constructs ,[object Object]
for  my $value (values(%hash)) { ... }  ,[object Object],[object Object],[object Object],[object Object]
Jump on loops ,[object Object]
Jump on loops: ,[object Object]
next LABEL : starts the next iteration of the loop
redo LABEL : restarts the loop block without evaluating the conditional again ,[object Object]
Inverting the cycle ,[object Object]
Warning:  last ,  next , and  redo  don't work in this case.
Exercises 1 - Scalars 1) Implement the ‘Guess the lucky number’. The program shall chose a random number between 0 and 100 and ask the user for a guess. Notice the user if the guess is bigger, smaller or equal to the random number. If the guess is correct the program shall leave otherwise re-ask for a number.
Exercises 1 - Array 2) Create an array that contains the names of 5 students of this class.  2a) Print the array.  2b) Create a new Array shifting the elements left by one positions (element 1 goes to 0, …) and setting the first element in the last position. Print the array.  2c) Ask a user to input a number. Print the name with that index.
Exercises 1 - Hash 3) Homer Family ,[object Object],3a) Print all the characters name’s.  3b) Demand for a name and print is position. 3c) Print all the characters position’s, no repetitions.  3d) Demand for a position and print the name.
Subroutines
Subroutines ,[object Object]
all subroutines likewise return to their caller one scalar or a list of scalars.
lists or hashes in these lists will collapse, losing their identities - but you may always pass a reference.
The subroutine name start with a  & , for simplification can be omitted.
Subroutine - example ,[object Object]
my $my_max =  max( 1, 9, 3, 7 ) ; print $my_max; # prints 9
Subroutine input and output ,[object Object]
Subroutine input and output ,[object Object]
Persistent Private Variables ,[object Object]
state variables ,[object Object]
Named Parameters ,[object Object]
Named Parameters ,[object Object]
Named Parameters ,[object Object]
Named Parameters ,[object Object]
Named Parameters ,[object Object]
Exercises 2 1) Create a new subroutine that calculates the Fibonacci series. Using this subroutine, do a program that receives multiple numbers as argument and prints the Fibonacci value. F(0) = 0 F(1) = 1 F(n) = F(n-1) + F(n-2) 1a) with presistent variable 1b) with state variable
IO
Read a File ,[object Object]
Open a Filehandler ,[object Object]
open (INFH, &quot; < input.txt&quot;)  or die $!;
open (INFH, &quot;input.txt&quot;)  or die $!; ,[object Object],[object Object]
open (OUTFH, &quot; > output.txt&quot;)  or die $!; ,[object Object],[object Object]
open (LOGFH, &quot; >> my.log&quot;)  or die $!;
Open a Filehandler ,[object Object]
a lexical scalar variable closes at the end of the block if it wasn't closed before ,[object Object],[object Object],[object Object],[object Object]
Write to a Filehandle ,[object Object]
print OUTFH  $record;
print { $FH }  $logMessage;
Note: There is no ‘,’ between filehandle and the text. ,[object Object],[object Object]
Read from a Filehandle ,[object Object]

Más contenido relacionado

La actualidad más candente (20)

Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Regular expression in javascript
Regular expression in javascriptRegular expression in javascript
Regular expression in javascript
 
Basic Input and Output
Basic Input and OutputBasic Input and Output
Basic Input and Output
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Java ppt
Java pptJava ppt
Java ppt
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Working with arrays in php
Working with arrays in phpWorking with arrays in php
Working with arrays in php
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
 
Hashing PPT
Hashing PPTHashing PPT
Hashing PPT
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 

Destacado

Introducing Modern Perl
Introducing Modern PerlIntroducing Modern Perl
Introducing Modern PerlDave Cross
 
Efficient Shared Data in Perl
Efficient Shared Data in PerlEfficient Shared Data in Perl
Efficient Shared Data in PerlPerrin Harkins
 
DBI Advanced Tutorial 2007
DBI Advanced Tutorial 2007DBI Advanced Tutorial 2007
DBI Advanced Tutorial 2007Tim Bunce
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applicationsJoe Jiang
 
Database Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDatabase Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDave Cross
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in PerlLaurent Dami
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 

Destacado (8)

Introducing Modern Perl
Introducing Modern PerlIntroducing Modern Perl
Introducing Modern Perl
 
Efficient Shared Data in Perl
Efficient Shared Data in PerlEfficient Shared Data in Perl
Efficient Shared Data in Perl
 
DBI Advanced Tutorial 2007
DBI Advanced Tutorial 2007DBI Advanced Tutorial 2007
DBI Advanced Tutorial 2007
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Database Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDatabase Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::Class
 
Working with databases
Working with databasesWorking with databases
Working with databases
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Similar a Perl Introduction

Beginning Perl
Beginning PerlBeginning Perl
Beginning PerlDave Cross
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlDave Cross
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2Dave Cross
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate PerlDave Cross
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisIan Macali
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kianphelios
 
Tutorial perl programming basic eng ver
Tutorial perl programming basic eng verTutorial perl programming basic eng ver
Tutorial perl programming basic eng verQrembiezs Intruder
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented PerlBunty Ray
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Languagezone
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoobirbal
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de JavascriptBernard Loire
 

Similar a Perl Introduction (20)

Beginning Perl
Beginning PerlBeginning Perl
Beginning 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
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
 
Php2
Php2Php2
Php2
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
 
Tutorial perl programming basic eng ver
Tutorial perl programming basic eng verTutorial perl programming basic eng ver
Tutorial perl programming basic eng ver
 
Cleancode
CleancodeCleancode
Cleancode
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented Perl
 
perltut
perltutperltut
perltut
 
perltut
perltutperltut
perltut
 
Php Learning show
Php Learning showPhp Learning show
Php Learning show
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Javascript
JavascriptJavascript
Javascript
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
 

Más de Marcos Rebelo

Store stream data on Data Lake
Store stream data on Data LakeStore stream data on Data Lake
Store stream data on Data LakeMarcos Rebelo
 
Coordinating external data importer services using AWS step functions
Coordinating external data importer services using AWS step functionsCoordinating external data importer services using AWS step functions
Coordinating external data importer services using AWS step functionsMarcos Rebelo
 
Perl In The Command Line
Perl In The Command LinePerl In The Command Line
Perl In The Command LineMarcos Rebelo
 

Más de Marcos Rebelo (6)

Store stream data on Data Lake
Store stream data on Data LakeStore stream data on Data Lake
Store stream data on Data Lake
 
Coordinating external data importer services using AWS step functions
Coordinating external data importer services using AWS step functionsCoordinating external data importer services using AWS step functions
Coordinating external data importer services using AWS step functions
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Perl5i
Perl5iPerl5i
Perl5i
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
Perl In The Command Line
Perl In The Command LinePerl In The Command Line
Perl In The Command Line
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Último (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

Perl Introduction

  • 1. Perl Welcome Pratical Extraction and Reporting Language Marcos Rebelo oleber@gmail.com
  • 2.
  • 3.
  • 4. There's More Than One Way to Do It
  • 5.
  • 6. Supports both procedural and OO programming.
  • 7. It has powerful built-in support for text processing
  • 8. It has one of the world's most impressive collections of third-party modules (http://www.cpan.org).
  • 9.
  • 10. Open Source, and free licencing
  • 11. Excellent text handling and regular expressions
  • 13. Fast, for an interpreted language
  • 14. Code developed is generally cross plaform
  • 15. Very easy to write powerful programs in a few lines of code
  • 16.
  • 17. Can look complicated, initially, particularly if you're not familiar with regular expressions
  • 18.
  • 20. Most command line applications
  • 23. Database access and manipulation
  • 24. Any application involving significant text processing
  • 25.
  • 26.
  • 27. You can use parentheses for subroutines arguments or omit them according to your personal taste. say &quot;Hello, world!&quot;;
  • 28. Comments start with a # and run to the end of the line. # This is a comment
  • 29.
  • 30. However, only double quotes interpolate variables and special characters such as newlines ( ): print(&quot;Hello, $name! &quot;); # interpolate $name print('Hello, $name! '); # prints $name! literally
  • 31.
  • 32. ... except inside quoted strings: print(&quot;Hello world&quot;); # this would print with a # line break in the middle.
  • 33.
  • 34.
  • 35. Alternatively, put this shebang in your script : #!/usr/bin/perl and run your executable script #> progname.pl
  • 36. -e : allows you to define the Perl code in the command line to be executed, -E to get 5.10 #> perl -e 'print(&quot;Hello, World! &quot;)'
  • 37.
  • 38. Arrays my @ animals = ('camel', 'lama'); my @ numbers = (23, 42, 69); my @ mixed = ('camel', 42, 1.23);
  • 39. Associative Array / Hash Tables my % fruit_color = ( apple => 'red', banana => 'yellow' );
  • 40.
  • 41. my $ answer = 42;
  • 42.
  • 43.
  • 44. my @ numbers = (23, 42, 69);
  • 45.
  • 46. print( $ numbers [-1] ); # prints 69
  • 47.
  • 48. @ numbers [0..2] ; # gives (23, 42, 69);
  • 49.
  • 50. @ numbers [2, 1] = @ numbers [1, 2] ;
  • 52.
  • 53. if ( scalar( @animals ) < 5) { ... }
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61. my @citiesPT = @{ $cities->{PT} } ;
  • 62.
  • 63.
  • 64.
  • 65.
  • 66. @ARGV : the command line arguments to your script.
  • 67. $ARGV : contains the name of the current file when reading from <> or readline() .
  • 68. @_ : the arguments passed to a subroutine.
  • 69. $a , $b : Special package variables when using sort() .
  • 70. $/ : The input record separator, newline by default.
  • 71.
  • 72. - -= subtraction
  • 73. * *= multiplication
  • 74.
  • 75. || or
  • 76. ! not
  • 77.
  • 78. . string concatenation
  • 79. x string multiplication
  • 80. .. range operator (creates a list of numbers)
  • 82.
  • 83. if COND BLOCK else BLOCK
  • 84. if COND BLOCK elsif COND BLOCK
  • 85.
  • 86.
  • 87. This is provided as a 'more readable' version of if ( not( is_valid( $value ) ) ) { ... }
  • 88. 0, '0', '', () and undef are all false in a boolean context. All other values are true.
  • 89.
  • 90. The Perlish post-condition way print(&quot;Yow!&quot;) if $zippy; print(&quot;No cubes&quot;) unless $cubes;
  • 91.
  • 92. There's also a negated version (don't use it): until ( is_valid( $value ) ) { … }
  • 93. You can also use while in a post-condition: print(&quot;xpto &quot;) while condition;
  • 94. Going throw a hash: while (my ($key,$value) = each (%ENV)){ print &quot;$key=$value &quot;; }
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100. next LABEL : starts the next iteration of the loop
  • 101.
  • 102.
  • 103. Warning: last , next , and redo don't work in this case.
  • 104. Exercises 1 - Scalars 1) Implement the ‘Guess the lucky number’. The program shall chose a random number between 0 and 100 and ask the user for a guess. Notice the user if the guess is bigger, smaller or equal to the random number. If the guess is correct the program shall leave otherwise re-ask for a number.
  • 105. Exercises 1 - Array 2) Create an array that contains the names of 5 students of this class. 2a) Print the array. 2b) Create a new Array shifting the elements left by one positions (element 1 goes to 0, …) and setting the first element in the last position. Print the array. 2c) Ask a user to input a number. Print the name with that index.
  • 106.
  • 108.
  • 109. all subroutines likewise return to their caller one scalar or a list of scalars.
  • 110. lists or hashes in these lists will collapse, losing their identities - but you may always pass a reference.
  • 111. The subroutine name start with a & , for simplification can be omitted.
  • 112.
  • 113. my $my_max = max( 1, 9, 3, 7 ) ; print $my_max; # prints 9
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123. Exercises 2 1) Create a new subroutine that calculates the Fibonacci series. Using this subroutine, do a program that receives multiple numbers as argument and prints the Fibonacci value. F(0) = 0 F(1) = 1 F(n) = F(n-1) + F(n-2) 1a) with presistent variable 1b) with state variable
  • 124. IO
  • 125.
  • 126.
  • 127. open (INFH, &quot; < input.txt&quot;) or die $!;
  • 128.
  • 129.
  • 130. open (LOGFH, &quot; >> my.log&quot;) or die $!;
  • 131.
  • 132.
  • 133.
  • 134. print OUTFH $record;
  • 135. print { $FH } $logMessage;
  • 136.
  • 137.
  • 138. Slurp: my @lines = <$fh> ; my @lines = readline($fh) ;
  • 139.
  • 140. foreach my $line (<$fh>) { # slurps print &quot;Just read: $line&quot;; }
  • 141.
  • 142. my $txt = do { local (@ARGV, $/) = ($myfile); readline(); };
  • 143.
  • 144.
  • 145. $ARGV has the open file, or '-' if reading STDIN .
  • 146.
  • 147. The __DATA__ token opens the DATA handle in whichever package is in effect at the time, so different modules can each have their own DATA filehandle, since they (presumably) have different package names.
  • 148.
  • 149. --line : printing the line number before the line.
  • 150.
  • 151.
  • 152.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158. The $ means match at the end of the string or before a newline at the end of the string. print 'Ends with World!' if /World!$/;
  • 159.
  • 160. / [yY][eE][sS] / - match 'yes' case-insensitively.
  • 161.
  • 162. / [0-9a-f] / i - matches a hexadecimal digit
  • 163.
  • 164. / [^0-9] / - matches a non-numeric character
  • 165. / [a^] at/ - matches 'aat' or '^at'; here '^' is ordinary
  • 166.
  • 167. $x = 'bcr'; / [$x] at/ - matches ‘bat’, ‘cat’, or ‘rat’ / [$x] at/ - matches ‘$at’ or ‘xat’ and not ‘bat’, … / [x] at/ - matches ‘at’, ‘bat’, ‘cat’, or ‘rat’
  • 168.
  • 169. D is a non-digit character [^d]
  • 170. s is a whitespace character [ f]
  • 171. S is non-whitespace character [^s]
  • 172. w is a word character [0-9a-zA-Z_]
  • 173. W is a non-word character [^w]
  • 174. The period '.' matches any character but [^ ]
  • 175.
  • 176. /[ ds ]/ - matches any digit or whitespace character
  • 177. / .. rt/ - matches any two chars, followed by 'rt'
  • 178. /end . / - matches 'end.'
  • 179. /end [.] / - same thing, matches 'end.‘
  • 180.
  • 181. Create a Regular Expression that match a 5 digit integer in octal format.
  • 182. Create a program that receives one regexp as the first parameter and a file list and prints the lines matching the regexp.
  • 183.
  • 184. + - one or more
  • 185. ? - zero or one
  • 186. {3} - matches exactly 3
  • 187. {3,6} - matches between 3 and 6
  • 188. {3,} - matches 3 or more
  • 189.
  • 190.
  • 191.
  • 192. At a given character position, the first alternative that allows the regex match to succeed will be the one that matches. 'cats' =~ /c | ca | cat | cats/; # matches 'c' 'cats' =~ /cats | cat | ca | c/; # matches 'cats'
  • 193.
  • 194. / ( ^a|b ) c/ - matches 'ac' at start of string or 'bc' anywhere.
  • 195. /house ( cat| ) / - matches either 'housecat' or 'house'.
  • 196. /house ( cat ( s| ) | ) / - matches either 'housecats' or 'housecat' or 'house'.
  • 197.
  • 198.
  • 199.
  • 200. %+ is ('NAME' => 'Michael')
  • 201. %- is ('NAME' => ['Michael','Jackson'])
  • 202. $1 is 'Michael'
  • 203. $2 is 'Jackson'
  • 204.
  • 205.
  • 206.
  • 207.
  • 208. $& - The string matched.
  • 209.
  • 210. Switch use qw(switch say); given ($foo) { when (undef) {say '$foo is undefined'} when ('foo') {say '$foo is the str &quot;foo&quot;'} when (/Milan/) {say '$foo matches /Milan/'} when ([1,3,5,7,9]) { say '$foo is an odd digit'; continue ; # Fall through } when ($_ < 100) {say '$foo less than 100'} when (&check) {say 'check($foo) is true'} default {die 'what shall I do with $foo?'} }
  • 211.
  • 212. when($foo) is equivalent to when($_ ~~ $foo)
  • 213. Smart Matching $a $b Matching Code Code Code $a == $b # not empty prototype if any Any Code $b->($a) # not empty prototype if any Hash Hash [sort keys %$a]~~[sort keys %$b] Hash Array grep {exists $a->{$_}} @$b Hash Regex grep /$b/, keys %$a Hash Any exists $a->{$b} Array Array arrays are identical, value by value Array Regex grep /$b/, @$a Array Num grep $_ == $b, @$a Array Any grep $_ eq $b, @$a Any undef !defined $a Any Regex $a =~ /$b/ Code() Code() $a->() eq $b->() Any Code() $b->() # ignoring $a Num numish $a == $b Any Str $a eq $b Any Num $a == $b Any Any $a eq $b
  • 214.
  • 215. Create a program that printout all the lines in a file substituting the numbers by #.
  • 216.
  • 217.
  • 218. RegExp /((.*))/ and /((.*?))/ /d{4,}/ /(ww)-(ww)-(ww)/ /W+/
  • 220.
  • 221. length(EXPR) - Returns the length in characters of the value of EXPR.
  • 222. sprintf(FORMAT, LIST) - Returns a string formatted by the usual printf conventions of C.
  • 223. abs(EXPR), cos(EXPR), int(EXPR), log(EXPR), sin(EXPR), sqrt(EXPR) - normal numeric subroutines.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230. Note: If EXPR is omitted, uses $_ .
  • 231.
  • 232. shift(ARRAY), unshift(ARRAY, LIST) - Pops/Pushes a value from/to the start of the ARRAY .
  • 233. Note: in the pop and shift if ARRAY is omitted, pops the @ARGV array in the main program, and the @_ array in subroutines. Avoid to use it.
  • 234.
  • 235.
  • 236.
  • 237.
  • 238.
  • 239.
  • 240.
  • 241.
  • 242. Providing a closure, the elements come in $a and $b . sort {$a <=> $b} (10,9,20) # 9, 10, 20
  • 243.
  • 244.
  • 245.
  • 246. my %a = ('a' => 1); exists ($a{'a'}) # true exists ($a{'b'}) # false
  • 247.
  • 248.
  • 249.
  • 250. eval BLOCK : evaluates the expression and catch's the exception.
  • 251. die EXPR : if out of eval prints the error and exits with the value of $!, otherwise sets the value in $@ and exits eval with undef.
  • 252. eval { $answer = $a / $b; }; warn $@ if $@;
  • 253.
  • 254. Create a subroutine that receives an array of scalars and return a new one just with the strings with length smaller than 20.
  • 255.
  • 256. The remaining in lower-case.
  • 258.
  • 259.
  • 260.
  • 261.
  • 262.
  • 263.
  • 264.
  • 265.
  • 266. our $VERSION = 05.22; Sets the version number. Importing like: use Some::Module 6.15;
  • 267.
  • 268. our @EXPORT_OK = qw($var2 &func2); Lists of symbols that are going to be exported by request (better practice).
  • 269. our ( $var1, $var2 ) = ( 1, 2 ); sub func1() {print(&quot;func1 &quot;);} sub func2() {print(&quot;func2 &quot;);} Definition of the symbols.
  • 270.
  • 271. The package name pass as the first parameter of the subroutine. Some::Module->func(); $name->func();
  • 272. This will not pass the module name inside the subroutine Some::Module::func(); &{&quot;${name}::func&quot;}();
  • 273.
  • 274. A class is simply a package that happens to provide methods to deal with object references.
  • 275. A method is simply a subroutine that expects an object reference (or a package name, for class methods) as the first argument.
  • 276.
  • 277.
  • 278.
  • 279.
  • 280. package Bat; use base qw(Animal); sub fly { return 1; }
  • 281.
  • 282.
  • 283.
  • 284. Create a set of classes to represent the animal fly capabilities. Shall have two methods fly and name(get/put), the constructor receives the animal name. Consider the following rules: dog is a animal animal doesn’t fly bird is a animal bird flies penguin is a bird penguin doesn’t fly
  • 285. Create a program to test them.
  • 287.
  • 288. warnings - Control optional warnings
  • 289. lib - Manipulate @INC at compile time
  • 290. base - Establish an ISA relationship with base class
  • 291. constant - Declare constants (consider Readonly)
  • 292. subs - Predeclare sub names
  • 293.
  • 294.
  • 295. Carp - better die() and warn()
  • 296. Cwd - pathname of current working directory
  • 297. Exporter - Implements default import method for modules
  • 298. POSIX
  • 299. IPC::Open3 - open a process for reading, writing, and error handling
  • 300. Time::HiRes - High resolution alarm, sleep, gettimeofday, interval timers
  • 301.
  • 302. LWP::UserAgent - Web user agent class
  • 303. HTTP::Request - HTTP style request message
  • 304. HTTP::Response - HTTP style response message
  • 305. LWP::Simple - Simple procedural interface to LWP
  • 306. LWP::Simple::Post - Single-method POST requests
  • 307. HTTP::Async - process multiple HTTP requests in parallel without blocking.
  • 308.
  • 309. Net::SLP - accessing the Service Location Protocol
  • 310. Net::POP3 - Post Office Protocol 3 Client
  • 311. Net::SMTP - Simple Mail Transfer Protocol Client
  • 312. MIME::Lite - low-calorie MIME generator
  • 313. JSON - JSON encoder/decoder
  • 314. JSON::XS – fast JSON serialising/deserialising
  • 315.
  • 316. Apache2::RequestIO - Perl API for Apache request record IO
  • 317. Apache2::RequestRec - Perl API for Apache request record accessors
  • 318. Apache2::RequestUtil - Perl API for Apache request record utils
  • 319. CGI - Handle Common Gateway Interface requests and responses
  • 320.
  • 321. MIME::Base64 - Encoding and decoding of base64 strings
  • 322. Digest::SHA - Perl extension for SHA-1/224/256/384/512
  • 323. Digest::MD5 - Perl interface to the MD5 Algorithm
  • 324. Crypt::DES - Perl DES encryption module
  • 325. Net::SSH - Perl extension for secure shell
  • 326.
  • 327. Test::More - yet another framework for writing test scripts
  • 328. Test::Exception - Test exception based code
  • 329. Test::Output - Utilities to test STDOUT and STDERR messages.
  • 330.
  • 331. DBD::* - Perl DBI Database Driver DBD::SQLite, DBD::CSV, DBD::Google, ...
  • 332. Template – Template toolkit
  • 333. HTML::Template - Perl module to use HTML Templates
  • 335.
  • 336.
  • 337.
  • 338. Q/A

Notas del editor

  1. Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, code generation and more. The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). Its major features are: it&apos;s easy to use. Supports both procedural and object-oriented (OO) programming. It has powerful built-in support for text processing. it has one of the world&apos;s most impressive collections of third-party modules (http://www.cpan.org).
  2. $ perldoc -f keys $ perldoc -f values
  3. $ perldoc perlref Array reference: $refArray1 = @array; $refArray2 = [ &amp;quot;Milan&amp;quot;, &amp;quot;Rome&amp;quot;]; Hash reference $refHash1 = \%hash; $refHash2 = { apple =&gt; &amp;quot;red&amp;quot;, banana =&gt; &amp;quot;yellow&amp;quot; };
  4. $ perldoc -f my Check the local and our manpages as well. $ perldoc -f our $ perldoc -f local
  5. $ perldoc strict $ perldoc warnings Good practice Start your script files with: use strict; use warnings
  6. $ perldoc perlvar
  7. and , or and not are also supported as operators in their own right. They&apos;re more readable than the C-style operators, but have different precedence to &amp;&amp; and friends.
  8. ” ab” . ”cd” is ”abcd” ” ab” x 3 is ”ababab” ( 1 .. 5 ) is (1, 2, 3, 4, 5)
  9. $ perldoc perlop Why do we have separate numeric and string comparisons? Because we don&apos;t have special variable types and Perl needs to know whether to sort numerically (where 99 is less than 100) or alphabetically (where 100 comes before 99).
  10. $ perldoc -f each
  11. $ perldoc perlsyn In th foreach loop the value in $var is really the value in the array, so something like $var += 2; would change the value in the @array. Using the magic variable $_ foreach ( 0 .. $max-1) { print(&amp;quot;This element is $_ &amp;quot;); }
  12. Read from the STDIN my $line = &lt;&gt;; chomp($line); Random Number $value = int(rand(1000));
  13. Remember: The Fibonacci series is formed by starting with 0 and 1 and then adding the latest two numbers to get the next one: fib(0) = 0 # definition fib(1) = 1 # definition fib(2) = fib(0) + fib(1) = 1 fib(3) = fib(1) + fib(2) = 2 fib(4) = fib(2) + fib(3) = 3 ...
  14. $ perldoc -f open $ perldoc perlfunc $ perldoc perlopentut open() is documented in extravagant detail in the perlfunc manpage and the perlopentut manpage.
  15. $ perldoc -f close When you&apos;re done with your filehandles, you should close() them. When using scalar variables, file handls will be closed automaticaly when you come out of the variable scope.
  16. $ perldoc -f local $/ works like awk&apos;s RS variable. The value of $/ is a string, not a regex. awk has to be better for something.
  17. Some examples: &amp;quot;hotdog&amp;quot; =~ /dog/; # matches &amp;quot;hotdog&amp;quot; =~ /^dog/; # doesn&apos;t match &amp;quot;hotdog&amp;quot; =~ /dog$/; # matches &amp;quot;hotdog &amp;quot; =~ /dog$/; # matches &amp;quot;hotdog&amp;quot; =~ /^hotdog$/; # matches
  18. $ perldoc -f split
  19. The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches. Most punctuation names have reasonable mnemonics. Nevertheless, if you wish to use long variable names, you need only say use English; at the top of your program. For $` , $&amp; and $&apos; you could use $PREMATCH , $MATCH or $POSTMATCH
  20. $perldoc -f oct $perldoc -f defined
  21. $perldoc -f pop $perldoc -f push $perldoc -f shift $perldoc -f unshift
  22. $perldoc -f join $perldoc -f sort
  23. $perldoc -f reverse
  24. $perldoc -f map
  25. $perldoc -f grep
  26. $perldoc -f each
  27. $perldoc -f exists The element is not autovivified if it doesn’t exist.
  28. $ perldoc -f our An our declares the variables to be valid globals within the enclosing block, file or eval. That is, it has the same scoping rules as a my declaration, but does not create a local variable.
  29. $ perldoc base $ perldoc Exporter
  30. $ perldoc perlmod $ perldoc perlmodlib $ perldoc perlmodinstall
  31. $ perldoc -f bless
  32. $ perldoc perlboot $ perldoc perltoot $ perldoc perlobj