SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
Data Types in Perl




Paolo Marcatili - Programmazione 09-10
Agenda

> Perl Basics
> Hello World
> Scalars
> Arrays
> Hashes




                                                 2
        Paolo Marcatili - Programmazione 09-10
Task Today




Paolo Marcatili - Programmazione 09-10
parsing

Parse a GO file
Extract gene names and function




                                                 4
        Paolo Marcatili - Programmazione 09-10
Perl Basics




Paolo Marcatili - Programmazione 09-10
PERL

Practical Extraction
and Reporting Language

 Handle text files
 Web (CGI)
 Small scripts

http://www.perltutorial.org/
                                                  6
         Paolo Marcatili - Programmazione 09-10
Install

Windows
http://www.activestate.com/activeperl/
Cygwin (linux emulation)


Linux / OS-X
Native




                                                    7
           Paolo Marcatili - Programmazione 09-10
Hello World!




Paolo Marcatili - Programmazione 09-10
First script

Open an editor (e.g. gedit)

#!/usr/bin/perl -w
use strict;
use warnings;
print "Hello World!n";


Save as -> first.pl


                                                     9
            Paolo Marcatili - Programmazione 09-10
How to run a script

Terminal -> move to the script folder

perl first.pl

or
chmod a+x first.pl <- now it is executable by
                      everyone
./first.pl <- ./ means ‘in this folder’


                                                    10
           Paolo Marcatili - Programmazione 09-10
Scalars




Paolo Marcatili - Programmazione 09-10
Scalars
my $scalar;
$scalar=5;
$scalar=$scalar+3;
$scalar= “scalar vale $scalarn”;
print $scalar;


> scalar vale 8




                                    12
Scalars - 2

 Scalar data can be number or string.
 In Perl, string and number can be used
  nearly interchangeable.

 Scalar variable is used to hold scalar data.
 Scalar variable starts with dollar sign ($)
  followed by Perl identifier.
 Perl identifier can contain
 alphanumeric and underscores.
 It is not allowed to start with a digit.



                                                 13
Examples
#floating-point values
my $x = 3.14;
my $y = -2.78;

#integer values
my $a = 1000;
my $b = -2000;

my $s = "2000"; # similar to $s = 2000;

#strings
my $str = "this is a string in Perl".
my $str2 = 'this is also as string too'.
                                           14
Operations
my $x = 5 + 9; # Add 5 and 9, and then store the result in $x
$x = 30 - 4; # Subtract 4 from 30 and then store the result in $x
$x = 3 * 7; # Multiply 3 and 7 and then store the result in $x
$x = 6 / 2; # Divide 6 by 2
$x = 2 ** 8; # two to the power of 8
$x = 3 % 2; # Remainder of 3 divided by 2
$x++; # Increase $x by 1
$x--; # Decrease $x by 1

my $y = $x; # Assign $x to $y
$x += $y; # Add $y to $x
$x -= $y; # Subtract $y from $x
$x .= $y; # Append $y onto $x


                                                                    15
Operations - 2
my $x = 3;
my $c = "he ";
my $s = $c x $x; # $c repeated $x times
my $b = "bye";
print $s . "n"; #print s and start a new line
# similar to
print "$sn";
my $a = $s . $b; # Concatenate $s and $b
print $a;
# Interpolation
my $x = 10;
my $s = "you get $x";
print $s;



                                                 16
Arrays




Paolo Marcatili - Programmazione 09-10
boxed scalars




   Scalar       Array




                        18
array - 1


("Perl","array","tutorial");
(5,7,9,10);
(5,7,9,"Perl","list");
(1..20);
();




                                19
array - 2

my @str_array=("Perl","array","tutorial");
my @num_array=(5,7,9,10);
my @mixed_array=(5,7,9,"Perl","list");
my @rg_array=(1..20);
my @empty_array=();


print $str_array[1]; # 1st element is [0]




                                             20
operations
my @int =(1,3,5,2);
push(@int,10); #add 10 to @int
print "@intn";

my $last = pop(@int); #remove 10 from @int
print "@intn";

unshift(@int,0); #add 0 to @int
print "@intn";
my $start = shift(@int); # add 0 to @int
print "@intn";



                                             21
on array

my @int =(1,3,5,2);

foreach my $element (@int){
print “element is $elementn”;
}

my @sorted=sort(@int);
foreach my $element (@sorted){
print “element is $elementn”;
}



                                 22
Hashes




Paolo Marcatili - Programmazione 09-10
Hashes
> Hashes are like array, they store collections of
  scalars
  ... but unlike arrays, indexing is by name (just like in
  real life!!!)

> Two components to each hash entry:
   > Key         example : name
   > Value       example : phone number

> Hashes denoted with %
   > Example : %phoneDirectory

> Elements are accessed using {} (like [] in arrays)

                                                         24
           Paolo Marcatili - Programmazione 09-10
Hashes continued ...
> Adding a new key-value pair
       $phoneDirectory{“Shirly”} = 7267975

   > Note the $ to specify “scalar” context!
> Each key can have only one value
       $phoneDirectory{“Shirly”} = 7265797
      # overwrites previous assignment


> Multiple keys can have the same value

> Accessing the value of a key
    $phoneNumber =$phoneDirectory{“Shirly”};

                                                     25
            Paolo Marcatili - Programmazione 09-10
Hashes and Foreach
> Foreach works in hashes as well!

   foreach $person (keys (%phoneDirectory) )
      {
     print “$person: $phoneDirectory{$person}”;
     }

> Never depend on the order you put key/values
  in the hash! Perl has its own magic to make
  hashes amazingly fast!!


                                                   26
          Paolo Marcatili - Programmazione 09-10
Hashes and Sorting
> The sort function works with hashes as well
> Sorting on the keys
   foreach $person (sort keys %phoneDirectory) {
         print “$person : $directory{$person}n”;
   }
   > This will print the phoneDirectory hash table in
      alphabetical order based on the name of the
      person,         i.e. the key.




                                                        27
           Paolo Marcatili - Programmazione 09-10
Hash and Sorting cont...
> Sorting by value

   foreach $person (sort {$phoneDirectory{$a} <=>
      $phoneDirectory{$b}} keys %phoneDirectory)
       {
         print “$person :
         $phoneDirectory{$person}n”;
       }

   > Prints the person and their phone number in the
     order of their respective phone numbers, i.e.
     the value.


                                                       28
          Paolo Marcatili - Programmazione 09-10
Exercise

> Chose your own test or use wget

> Identify the 10 most frequent words

> Sort the words alphabetically

> Sort the words by the number of
  occurrences

                                                 29
        Paolo Marcatili - Programmazione 09-10
Counting Words
my %seen;
  my $l=“Lorem ipsum”;
  my @w=split (“ “, $l);# questa è una funzione nuova…
  foreach my $word (@w){
       $seen{$word}++;
  }
  print “Sorted by occurrencesn”;
  foreach my $word (sort {$seen{$a}<=>$seen{$b}} keys %seen){
      print “Word $word N: $seen{$word}n”;
  }

  print “Sorted alphabeticallyn”;
  foreach my $word (sort ( keys %seen)){
  print “Word $word N: $seen{$word}n”;
  }

                                                                30
             Paolo Marcatili - Programmazione 09-10

Weitere ähnliche Inhalte

Was ist angesagt?

How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrowPete McFarlane
 
Business Rules with Brick
Business Rules with BrickBusiness Rules with Brick
Business Rules with Brickbrian d foy
 
[2019] 아직도 돈 주고 DB 쓰나요? for Developer
[2019] 아직도 돈 주고 DB 쓰나요? for Developer[2019] 아직도 돈 주고 DB 쓰나요? for Developer
[2019] 아직도 돈 주고 DB 쓰나요? for DeveloperNHN FORWARD
 
Linux shell script-1
Linux shell script-1Linux shell script-1
Linux shell script-1兎 伊藤
 
Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"Fwdays
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using CodeceptionJeroen van Dijk
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsDavid Golden
 
PHP object calisthenics
PHP object calisthenicsPHP object calisthenics
PHP object calisthenicsGiorgio Cefaro
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHPGuilherme Blanco
 

Was ist angesagt? (18)

How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Business Rules with Brick
Business Rules with BrickBusiness Rules with Brick
Business Rules with Brick
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
[2019] 아직도 돈 주고 DB 쓰나요? for Developer
[2019] 아직도 돈 주고 DB 쓰나요? for Developer[2019] 아직도 돈 주고 DB 쓰나요? for Developer
[2019] 아직도 돈 주고 DB 쓰나요? for Developer
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Linux shell script-1
Linux shell script-1Linux shell script-1
Linux shell script-1
 
Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"
 
07 php
07 php07 php
07 php
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Web 10 | PHP with MySQL
Web 10 | PHP with MySQLWeb 10 | PHP with MySQL
Web 10 | PHP with MySQL
 
Php variables
Php variablesPhp variables
Php variables
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
Web 4 | Core JavaScript
Web 4 | Core JavaScriptWeb 4 | Core JavaScript
Web 4 | Core JavaScript
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
 
PHP object calisthenics
PHP object calisthenicsPHP object calisthenics
PHP object calisthenics
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 

Ähnlich wie Data Types Master

Ähnlich wie Data Types Master (20)

Hashes Master
Hashes MasterHashes Master
Hashes Master
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Creating a compiler in Perl 6
Creating a compiler in Perl 6Creating a compiler in Perl 6
Creating a compiler in Perl 6
 
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
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
32 shell-programming
32 shell-programming32 shell-programming
32 shell-programming
 
Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01
 
Mips1
Mips1Mips1
Mips1
 
Bag of tricks
Bag of tricksBag of tricks
Bag of tricks
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
tutorial7
tutorial7tutorial7
tutorial7
 
tutorial7
tutorial7tutorial7
tutorial7
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Mehr von Paolo Marcatili

Mehr von Paolo Marcatili (8)

Regexp master 2011
Regexp master 2011Regexp master 2011
Regexp master 2011
 
Master perl io_2011
Master perl io_2011Master perl io_2011
Master perl io_2011
 
Master datatypes 2011
Master datatypes 2011Master datatypes 2011
Master datatypes 2011
 
Master unix 2011
Master unix 2011Master unix 2011
Master unix 2011
 
Machine Learning
Machine LearningMachine Learning
Machine Learning
 
Regexp Master
Regexp MasterRegexp Master
Regexp Master
 
Perl Io Master
Perl Io MasterPerl Io Master
Perl Io Master
 
Unix Master
Unix MasterUnix Master
Unix Master
 

Kürzlich hochgeladen

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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
 

Kürzlich hochgeladen (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 

Data Types Master

  • 1. Data Types in Perl Paolo Marcatili - Programmazione 09-10
  • 2. Agenda > Perl Basics > Hello World > Scalars > Arrays > Hashes 2 Paolo Marcatili - Programmazione 09-10
  • 3. Task Today Paolo Marcatili - Programmazione 09-10
  • 4. parsing Parse a GO file Extract gene names and function 4 Paolo Marcatili - Programmazione 09-10
  • 5. Perl Basics Paolo Marcatili - Programmazione 09-10
  • 6. PERL Practical Extraction and Reporting Language  Handle text files  Web (CGI)  Small scripts http://www.perltutorial.org/ 6 Paolo Marcatili - Programmazione 09-10
  • 7. Install Windows http://www.activestate.com/activeperl/ Cygwin (linux emulation) Linux / OS-X Native 7 Paolo Marcatili - Programmazione 09-10
  • 8. Hello World! Paolo Marcatili - Programmazione 09-10
  • 9. First script Open an editor (e.g. gedit) #!/usr/bin/perl -w use strict; use warnings; print "Hello World!n"; Save as -> first.pl 9 Paolo Marcatili - Programmazione 09-10
  • 10. How to run a script Terminal -> move to the script folder perl first.pl or chmod a+x first.pl <- now it is executable by everyone ./first.pl <- ./ means ‘in this folder’ 10 Paolo Marcatili - Programmazione 09-10
  • 11. Scalars Paolo Marcatili - Programmazione 09-10
  • 12. Scalars my $scalar; $scalar=5; $scalar=$scalar+3; $scalar= “scalar vale $scalarn”; print $scalar; > scalar vale 8 12
  • 13. Scalars - 2  Scalar data can be number or string.  In Perl, string and number can be used nearly interchangeable.  Scalar variable is used to hold scalar data.  Scalar variable starts with dollar sign ($) followed by Perl identifier.  Perl identifier can contain alphanumeric and underscores.  It is not allowed to start with a digit. 13
  • 14. Examples #floating-point values my $x = 3.14; my $y = -2.78; #integer values my $a = 1000; my $b = -2000; my $s = "2000"; # similar to $s = 2000; #strings my $str = "this is a string in Perl". my $str2 = 'this is also as string too'. 14
  • 15. Operations my $x = 5 + 9; # Add 5 and 9, and then store the result in $x $x = 30 - 4; # Subtract 4 from 30 and then store the result in $x $x = 3 * 7; # Multiply 3 and 7 and then store the result in $x $x = 6 / 2; # Divide 6 by 2 $x = 2 ** 8; # two to the power of 8 $x = 3 % 2; # Remainder of 3 divided by 2 $x++; # Increase $x by 1 $x--; # Decrease $x by 1 my $y = $x; # Assign $x to $y $x += $y; # Add $y to $x $x -= $y; # Subtract $y from $x $x .= $y; # Append $y onto $x 15
  • 16. Operations - 2 my $x = 3; my $c = "he "; my $s = $c x $x; # $c repeated $x times my $b = "bye"; print $s . "n"; #print s and start a new line # similar to print "$sn"; my $a = $s . $b; # Concatenate $s and $b print $a; # Interpolation my $x = 10; my $s = "you get $x"; print $s; 16
  • 17. Arrays Paolo Marcatili - Programmazione 09-10
  • 18. boxed scalars Scalar Array 18
  • 20. array - 2 my @str_array=("Perl","array","tutorial"); my @num_array=(5,7,9,10); my @mixed_array=(5,7,9,"Perl","list"); my @rg_array=(1..20); my @empty_array=(); print $str_array[1]; # 1st element is [0] 20
  • 21. operations my @int =(1,3,5,2); push(@int,10); #add 10 to @int print "@intn"; my $last = pop(@int); #remove 10 from @int print "@intn"; unshift(@int,0); #add 0 to @int print "@intn"; my $start = shift(@int); # add 0 to @int print "@intn"; 21
  • 22. on array my @int =(1,3,5,2); foreach my $element (@int){ print “element is $elementn”; } my @sorted=sort(@int); foreach my $element (@sorted){ print “element is $elementn”; } 22
  • 23. Hashes Paolo Marcatili - Programmazione 09-10
  • 24. Hashes > Hashes are like array, they store collections of scalars ... but unlike arrays, indexing is by name (just like in real life!!!) > Two components to each hash entry: > Key example : name > Value example : phone number > Hashes denoted with % > Example : %phoneDirectory > Elements are accessed using {} (like [] in arrays) 24 Paolo Marcatili - Programmazione 09-10
  • 25. Hashes continued ... > Adding a new key-value pair $phoneDirectory{“Shirly”} = 7267975 > Note the $ to specify “scalar” context! > Each key can have only one value $phoneDirectory{“Shirly”} = 7265797 # overwrites previous assignment > Multiple keys can have the same value > Accessing the value of a key $phoneNumber =$phoneDirectory{“Shirly”}; 25 Paolo Marcatili - Programmazione 09-10
  • 26. Hashes and Foreach > Foreach works in hashes as well! foreach $person (keys (%phoneDirectory) ) { print “$person: $phoneDirectory{$person}”; } > Never depend on the order you put key/values in the hash! Perl has its own magic to make hashes amazingly fast!! 26 Paolo Marcatili - Programmazione 09-10
  • 27. Hashes and Sorting > The sort function works with hashes as well > Sorting on the keys foreach $person (sort keys %phoneDirectory) { print “$person : $directory{$person}n”; } > This will print the phoneDirectory hash table in alphabetical order based on the name of the person, i.e. the key. 27 Paolo Marcatili - Programmazione 09-10
  • 28. Hash and Sorting cont... > Sorting by value foreach $person (sort {$phoneDirectory{$a} <=> $phoneDirectory{$b}} keys %phoneDirectory) { print “$person : $phoneDirectory{$person}n”; } > Prints the person and their phone number in the order of their respective phone numbers, i.e. the value. 28 Paolo Marcatili - Programmazione 09-10
  • 29. Exercise > Chose your own test or use wget > Identify the 10 most frequent words > Sort the words alphabetically > Sort the words by the number of occurrences 29 Paolo Marcatili - Programmazione 09-10
  • 30. Counting Words my %seen; my $l=“Lorem ipsum”; my @w=split (“ “, $l);# questa è una funzione nuova… foreach my $word (@w){ $seen{$word}++; } print “Sorted by occurrencesn”; foreach my $word (sort {$seen{$a}<=>$seen{$b}} keys %seen){ print “Word $word N: $seen{$word}n”; } print “Sorted alphabeticallyn”; foreach my $word (sort ( keys %seen)){ print “Word $word N: $seen{$word}n”; } 30 Paolo Marcatili - Programmazione 09-10