SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Read and Write Files
                        with Perl




Bioinformatics master course, „11/‟12   Paolo Marcatili
Resume
 •   Scalars                   $
 •   Arrays                    @
 •   Hashes                      %
 •   Foreach                    |-@ $
 •   Length                    …
 •   Split                    $@



Bioinformatics master course, „11/‟12    Paolo Marcatili
Agenda
 •   For
 •   Conditions
 •   Perl IO
 •   Open a File
 •   Write on Files
 •   Read from Files
 •   While loop

Bioinformatics master course, „11/‟12   Paolo Marcatili
New cycle!
 for (my $i=0;$i<100;$i++){
    print “$i n”;
 }

 Can we rewrite foreach using for?

 Hint: scalar @array is the array size

Bioinformatics master course, „11/‟12   Paolo Marcatili
Conditions
 if (condition){
 Do something
 }




Bioinformatics master course, „11/‟12   Paolo Marcatili
Conditions
 if ($time>5){
 print “Time to go!n”;
 }




Bioinformatics master course, „11/‟12   Paolo Marcatili
Conditions
 if ($day == 27){
 print “Wage!n”;
 }




Bioinformatics master course, „11/‟12   Paolo Marcatili
Conditions
 if ($day eq “Sunday”){
 print “Alarm off!n”;
 }
 else{

 print “snoozen”;

 }

Bioinformatics master course, „11/‟12   Paolo Marcatili
Perl IO

                     (IO means Input/Output)




Bioinformatics master course, „11/‟12         Paolo Marcatili
Why IO?
 Since now, Perl is

 #! /usr/bin/perl -w
 use strict; #<- ALWAYS!!!
 my $string=”All work and no play makes Jack a
   dull boyn";
 for (my $i=1;$i<100;$i++){
    print $string;
 }


Bioinformatics master course, „11/‟12   Paolo Marcatili
Why IO?
 But if we want to do the same
 with a user-submitted string?




Bioinformatics master course, „11/‟12   Paolo Marcatili
Why IO?
 But if we want to do the same
 with a user-submitted string?


 IO can do this!




Bioinformatics master course, „11/‟12   Paolo Marcatili
IO types
 Main Inputs
 • Keyboard
 • File
 • Errors
 Main outputs
 • Display
 • File


Bioinformatics master course, „11/‟12   Paolo Marcatili
More than tomatoes
 Let‟s try it:

 #! /usr/bin/perl -w
   use strict; my $string=<STDIN>;
   for (my $i=1;$i<100;$i++){
    print $string;
   }


Bioinformatics master course, „11/‟12   Paolo Marcatili
Rationale
 Read from and write to different media

 STDIN means standard input (keyboard)
     ^
      this is a handle
 <SMTH> means
 “read from the source corresponding to handle SMTH”




Bioinformatics master course, „11/‟12   Paolo Marcatili
Handles
 Handles are just streams “nicknames”
 Some of them are fixed:
 STDIN     <-default is keyboard
 STDOUT <-default is display
 STDERR <-default is display
 Some are user defined (files)



Bioinformatics master course, „11/‟12   Paolo Marcatili
Open/Write a file




Bioinformatics master course, „11/‟12   Paolo Marcatili
open
 We have to create a handle for our file
 open(OUT, “>”,”out.txt”) or die(“Error opening out.txt: $!”);
        ^
     N.B. : it‟s user defined, you decide it
 Tip
 “<“,”out.txt” <- read from out.txt
 “>”,”out.txt” <- write into out.txt
 “>>”,”out.txt” <- append to out.txt


Bioinformatics master course, „11/‟12          Paolo Marcatili
close
 When finished we have to close it:
 close OUT;

 If you dont, Santa will bring no gift.




Bioinformatics master course, „11/‟12           Paolo Marcatili
Print OUT
 #! /usr/bin/perl -w
 use strict;
 open(OUT, ">”,”out.txt") || die("Error opening out.txt: $!");
 print "type your claim:n";
 my $string=<STDIN>;
 for (my $i=1;$i<100;$i++){
    print OUT $string;
 }
 close OUT;

 Now let‟s play with <,>,>> and file permissions

Bioinformatics master course, „11/‟12   Paolo Marcatili
Read from Files




Bioinformatics master course, „11/‟12   Paolo Marcatili
Read
 open(IN, “<song.txt”) or die(“Error opening song.txt: $!”);
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;
 print <IN>;

 close IN;



Bioinformatics master course, „11/‟12          Paolo Marcatili
Read with loops
 Problems:
 • It‟s long
 • File size unknown

 solution:
 Use loops



Bioinformatics master course, „11/‟12   Paolo Marcatili
While loop




Bioinformatics master course, „11/‟12   Paolo Marcatili
While

 while (condition){
               do something…

 }




Bioinformatics master course, „11/‟12      Paolo Marcatili
While - for differences
   While                                For

   • Undetermined                       > Determined
   • No counter                         > Counter




Bioinformatics master course, „11/‟12         Paolo Marcatili
While example
   Approx. solution of x^2-2=0
   (Newton‟s method)

   my $sol=0.5;
   my $err=$sol**2-2;
   while ($err**2>.001){
   $sol-=($sol**2-2)/(2*$sol);
   $err=$sol**2-2;
   print “X is $solnError=$errn”;
   }
Bioinformatics master course, „11/‟12   Paolo Marcatili
Read with while
   #! /usr/bin/perl -w
   use strict;
   open(MOD, "<IG.pdb") || die("Error opening
      IG.pdb: $!");

   while (my $line=<MOD>){
      print substr($line,0,6)."n";
   }
   close MOD;




Bioinformatics master course, „11/‟12   Paolo Marcatili
Redirect outputs




Bioinformatics master course, „11/‟12   Paolo Marcatili
Redirections
     #!/usr/bin/perl
     open(STDOUT, ">foo.out") || die "Can't redirect stdout";
     open(STDERR, ">&STDOUT") || die "Can't dup stdout";

     select(STDERR); $| = 1;            # make unbuffered
     select(STDOUT); $| = 1;            # make unbuffered

     close(STDOUT);
     close(STDERR);




Bioinformatics master course, „11/‟12        Paolo Marcatili
@ARGV




Bioinformatics master course, „11/‟12   Paolo Marcatili
Command Line Arguments
 •   Command line arguments in Perl are extremely easy.
 •   @ARGV is the array that holds all arguments passed in from the
     command line.
      – Example:
            • % ./prog.pl arg1 arg2 arg3
      – @ARGV would contain ('arg1', arg2', 'arg3)


 •   $#ARGV returns the number of command line arguments that have
     been passed.
      – Remember $#array is the size of the array -1 !




Bioinformatics master course, „11/‟12           Paolo Marcatili
Quick Program with @ARGV
 • Simple program called log.pl that takes in a number and
   prints the log base 2 of that number;

          #!/usr/local/bin/perl -w
          $log = log($ARGV[0]) / log(2);
          print “The log base 2 of $ARGV[0] is $log.n”;


 • Run the program as follows:
      – % log.pl 8
 • This will return the following:
      – The log base 2 of 8 is 3.



Bioinformatics master course, „11/‟12          Paolo Marcatili
$_
 • Perl default scalar value that is used when a
   variable is not explicitly specified.
 • Can be used in
      – For Loops
      – File Handling
      – Regular Expressions




Bioinformatics master course, „11/‟12        Paolo Marcatili
$_ and For Loops
 •   Example using $_ in a for loop

      @array = ( “Perl”, “C”, “Java” );
      for(@array) {
          print $_ . “is a language I known”;
      }

      – Output :
        Perl is a language I know.
        C is a language I know.
        Java is a language I know.




Bioinformatics master course, „11/‟12            Paolo Marcatili
$_ and File Handlers
 • Example in using $_ when reading in a file;

      while( <> ) {
           chomp $_;               # remove the newline char
           @array = split/ /, $_; # split the line on white space
               # and stores data in an array
      }

 • Note:
      – The line read in from the file is automatically store in the default
        scalar variable $_




Bioinformatics master course, „11/‟12          Paolo Marcatili
Opendir, readdir




Bioinformatics master course, „11/‟12   Paolo Marcatili
Opendir& readdir
     • Just like open, but for dirs

     # load all files of the "data/" folder into the @files array
     opendir(DIR, ”$ARGV[0]");
     @files = readdir(DIR);
     closedir(DIR);

     # build a unsorted list from the @files array:
     print "<ul>";
      foreach $file (@files) {
        next if ($file eq "." or $file eq "..");
        print "<li><a href="$file">$file</a></li>";
     }
      print "</ul>";


Bioinformatics master course, „11/‟12            Paolo Marcatili

Weitere ähnliche Inhalte

Was ist angesagt?

Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Workhorse Computing
 
What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5Tom Corrigan
 
Building and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CBuilding and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CDavid Wheeler
 
Linux Shellcode disassembling
Linux Shellcode disassemblingLinux Shellcode disassembling
Linux Shellcode disassemblingHarsh Daftary
 
Java Bytecode Fundamentals - JUG.lv
Java Bytecode Fundamentals - JUG.lvJava Bytecode Fundamentals - JUG.lv
Java Bytecode Fundamentals - JUG.lvAnton Arhipov
 
CLI, the other SAPI phpnw11
CLI, the other SAPI phpnw11CLI, the other SAPI phpnw11
CLI, the other SAPI phpnw11Combell NV
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLsAugusto Pascutti
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Workhorse Computing
 
Cli the other sapi pbc11
Cli the other sapi pbc11Cli the other sapi pbc11
Cli the other sapi pbc11Combell NV
 
An introduction to PHP 5.4
An introduction to PHP 5.4An introduction to PHP 5.4
An introduction to PHP 5.4Giovanni Derks
 
Preparing code for Php 7 workshop
Preparing code for Php 7 workshopPreparing code for Php 7 workshop
Preparing code for Php 7 workshopDamien Seguy
 
07 - Bypassing ASLR, or why X^W matters
07 - Bypassing ASLR, or why X^W matters07 - Bypassing ASLR, or why X^W matters
07 - Bypassing ASLR, or why X^W mattersAlexandre Moneger
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPwahidullah mudaser
 

Was ist angesagt? (20)

Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.
 
What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5
 
Building and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CBuilding and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning C
 
Findbin libs
Findbin libsFindbin libs
Findbin libs
 
Linux Shellcode disassembling
Linux Shellcode disassemblingLinux Shellcode disassembling
Linux Shellcode disassembling
 
Java Bytecode Fundamentals - JUG.lv
Java Bytecode Fundamentals - JUG.lvJava Bytecode Fundamentals - JUG.lv
Java Bytecode Fundamentals - JUG.lv
 
Codes
CodesCodes
Codes
 
CLI, the other SAPI phpnw11
CLI, the other SAPI phpnw11CLI, the other SAPI phpnw11
CLI, the other SAPI phpnw11
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLs
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!
 
Short Introduction To "perl -d"
Short Introduction To "perl -d"Short Introduction To "perl -d"
Short Introduction To "perl -d"
 
Cli the other sapi pbc11
Cli the other sapi pbc11Cli the other sapi pbc11
Cli the other sapi pbc11
 
Training on php by cyber security infotech (csi)
Training on  php by cyber security infotech (csi)Training on  php by cyber security infotech (csi)
Training on php by cyber security infotech (csi)
 
An introduction to PHP 5.4
An introduction to PHP 5.4An introduction to PHP 5.4
An introduction to PHP 5.4
 
Preparing code for Php 7 workshop
Preparing code for Php 7 workshopPreparing code for Php 7 workshop
Preparing code for Php 7 workshop
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
Illustrated buffer cache
Illustrated buffer cacheIllustrated buffer cache
Illustrated buffer cache
 
07 - Bypassing ASLR, or why X^W matters
07 - Bypassing ASLR, or why X^W matters07 - Bypassing ASLR, or why X^W matters
07 - Bypassing ASLR, or why X^W matters
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 

Andere mochten auch

大同大學附近商家人力資源問卷雷達圖
大同大學附近商家人力資源問卷雷達圖大同大學附近商家人力資源問卷雷達圖
大同大學附近商家人力資源問卷雷達圖ChiChi
 
人力資源管理導論(Click here to download)
人力資源管理導論(Click here to download)人力資源管理導論(Click here to download)
人力資源管理導論(Click here to download)ChiChi
 
01 職場人力現況分析(按此下載)
01 職場人力現況分析(按此下載)01 職場人力現況分析(按此下載)
01 職場人力現況分析(按此下載)ChiChi
 
03 國際貨幣制度與匯兌(按此下載)
03 國際貨幣制度與匯兌(按此下載)03 國際貨幣制度與匯兌(按此下載)
03 國際貨幣制度與匯兌(按此下載)ChiChi
 
07 履歷表實作 (按此下載)
07 履歷表實作 (按此下載)07 履歷表實作 (按此下載)
07 履歷表實作 (按此下載)ChiChi
 
招募 甄選Recruitment & Selection (按此下載)
招募 甄選Recruitment & Selection (按此下載)招募 甄選Recruitment & Selection (按此下載)
招募 甄選Recruitment & Selection (按此下載)ChiChi
 
11員工福利管理
11員工福利管理11員工福利管理
11員工福利管理ChiChi
 
05 國際經營策略與組織結構(按此下載)
05 國際經營策略與組織結構(按此下載)05 國際經營策略與組織結構(按此下載)
05 國際經營策略與組織結構(按此下載)ChiChi
 
人力資源管理 概念及趨勢
人力資源管理 概念及趨勢人力資源管理 概念及趨勢
人力資源管理 概念及趨勢ChiChi
 
05 如何寫一份漂亮的履歷表 (按此下載)
05 如何寫一份漂亮的履歷表 (按此下載)05 如何寫一份漂亮的履歷表 (按此下載)
05 如何寫一份漂亮的履歷表 (按此下載)ChiChi
 
10薪酬管理
10薪酬管理10薪酬管理
10薪酬管理ChiChi
 
工作分析 工作設計
工作分析 工作設計工作分析 工作設計
工作分析 工作設計ChiChi
 
溝通Communication(按此下載)
溝通Communication(按此下載)溝通Communication(按此下載)
溝通Communication(按此下載)ChiChi
 
04人力資源招募與甄選
04人力資源招募與甄選04人力資源招募與甄選
04人力資源招募與甄選ChiChi
 

Andere mochten auch (19)

大同大學附近商家人力資源問卷雷達圖
大同大學附近商家人力資源問卷雷達圖大同大學附近商家人力資源問卷雷達圖
大同大學附近商家人力資源問卷雷達圖
 
Unix Master
Unix MasterUnix Master
Unix Master
 
Regexp Master
Regexp MasterRegexp Master
Regexp Master
 
Data Types Master
Data Types MasterData Types Master
Data Types Master
 
Machine Learning
Machine LearningMachine Learning
Machine Learning
 
人力資源管理導論(Click here to download)
人力資源管理導論(Click here to download)人力資源管理導論(Click here to download)
人力資源管理導論(Click here to download)
 
01 職場人力現況分析(按此下載)
01 職場人力現況分析(按此下載)01 職場人力現況分析(按此下載)
01 職場人力現況分析(按此下載)
 
Perl Io Master
Perl Io MasterPerl Io Master
Perl Io Master
 
03 國際貨幣制度與匯兌(按此下載)
03 國際貨幣制度與匯兌(按此下載)03 國際貨幣制度與匯兌(按此下載)
03 國際貨幣制度與匯兌(按此下載)
 
07 履歷表實作 (按此下載)
07 履歷表實作 (按此下載)07 履歷表實作 (按此下載)
07 履歷表實作 (按此下載)
 
招募 甄選Recruitment & Selection (按此下載)
招募 甄選Recruitment & Selection (按此下載)招募 甄選Recruitment & Selection (按此下載)
招募 甄選Recruitment & Selection (按此下載)
 
11員工福利管理
11員工福利管理11員工福利管理
11員工福利管理
 
05 國際經營策略與組織結構(按此下載)
05 國際經營策略與組織結構(按此下載)05 國際經營策略與組織結構(按此下載)
05 國際經營策略與組織結構(按此下載)
 
人力資源管理 概念及趨勢
人力資源管理 概念及趨勢人力資源管理 概念及趨勢
人力資源管理 概念及趨勢
 
05 如何寫一份漂亮的履歷表 (按此下載)
05 如何寫一份漂亮的履歷表 (按此下載)05 如何寫一份漂亮的履歷表 (按此下載)
05 如何寫一份漂亮的履歷表 (按此下載)
 
10薪酬管理
10薪酬管理10薪酬管理
10薪酬管理
 
工作分析 工作設計
工作分析 工作設計工作分析 工作設計
工作分析 工作設計
 
溝通Communication(按此下載)
溝通Communication(按此下載)溝通Communication(按此下載)
溝通Communication(按此下載)
 
04人力資源招募與甄選
04人力資源招募與甄選04人力資源招募與甄選
04人力資源招募與甄選
 

Ähnlich wie Master perl io_2011

Ähnlich wie Master perl io_2011 (20)

Perl IO
Perl IOPerl IO
Perl IO
 
Master datatypes 2011
Master datatypes 2011Master datatypes 2011
Master datatypes 2011
 
Regexp master 2011
Regexp master 2011Regexp master 2011
Regexp master 2011
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
groovy & grails - lecture 2
groovy & grails - lecture 2groovy & grails - lecture 2
groovy & grails - lecture 2
 
Getting modern with logging via log4perl
Getting modern with logging via log4perlGetting modern with logging via log4perl
Getting modern with logging via log4perl
 
Master unix 2011
Master unix 2011Master unix 2011
Master unix 2011
 
The Essential Perl Hacker's Toolkit
The Essential Perl Hacker's ToolkitThe Essential Perl Hacker's Toolkit
The Essential Perl Hacker's Toolkit
 
Perl basics for Pentesters
Perl basics for PentestersPerl basics for Pentesters
Perl basics for Pentesters
 
Bioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekingeBioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekinge
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting CraftsmanshipLinux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introduction
 
Perl Intro 8 File Handles
Perl Intro 8 File HandlesPerl Intro 8 File Handles
Perl Intro 8 File Handles
 
Perl Intro 2 First Program
Perl Intro 2 First ProgramPerl Intro 2 First Program
Perl Intro 2 First Program
 
55j7
55j755j7
55j7
 
Getting testy with Perl
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
 
Perl Moderno
Perl ModernoPerl Moderno
Perl Moderno
 
Whatsnew in-perl
Whatsnew in-perlWhatsnew in-perl
Whatsnew in-perl
 
2010 Smith Scripting101
2010 Smith Scripting1012010 Smith Scripting101
2010 Smith Scripting101
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 

Kürzlich hochgeladen

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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 
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
 
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
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Kürzlich hochgeladen (20)

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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
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
 
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
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
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...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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...
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Master perl io_2011

  • 1. Read and Write Files with Perl Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 2. Resume • Scalars $ • Arrays @ • Hashes % • Foreach |-@ $ • Length … • Split $@ Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 3. Agenda • For • Conditions • Perl IO • Open a File • Write on Files • Read from Files • While loop Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 4. New cycle! for (my $i=0;$i<100;$i++){ print “$i n”; } Can we rewrite foreach using for? Hint: scalar @array is the array size Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 5. Conditions if (condition){ Do something } Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 6. Conditions if ($time>5){ print “Time to go!n”; } Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 7. Conditions if ($day == 27){ print “Wage!n”; } Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 8. Conditions if ($day eq “Sunday”){ print “Alarm off!n”; } else{ print “snoozen”; } Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 9. Perl IO (IO means Input/Output) Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 10. Why IO? Since now, Perl is #! /usr/bin/perl -w use strict; #<- ALWAYS!!! my $string=”All work and no play makes Jack a dull boyn"; for (my $i=1;$i<100;$i++){ print $string; } Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 11. Why IO? But if we want to do the same with a user-submitted string? Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 12. Why IO? But if we want to do the same with a user-submitted string? IO can do this! Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 13. IO types Main Inputs • Keyboard • File • Errors Main outputs • Display • File Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 14. More than tomatoes Let‟s try it: #! /usr/bin/perl -w use strict; my $string=<STDIN>; for (my $i=1;$i<100;$i++){ print $string; } Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 15. Rationale Read from and write to different media STDIN means standard input (keyboard) ^ this is a handle <SMTH> means “read from the source corresponding to handle SMTH” Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 16. Handles Handles are just streams “nicknames” Some of them are fixed: STDIN <-default is keyboard STDOUT <-default is display STDERR <-default is display Some are user defined (files) Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 17. Open/Write a file Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 18. open We have to create a handle for our file open(OUT, “>”,”out.txt”) or die(“Error opening out.txt: $!”); ^ N.B. : it‟s user defined, you decide it Tip “<“,”out.txt” <- read from out.txt “>”,”out.txt” <- write into out.txt “>>”,”out.txt” <- append to out.txt Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 19. close When finished we have to close it: close OUT; If you dont, Santa will bring no gift. Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 20. Print OUT #! /usr/bin/perl -w use strict; open(OUT, ">”,”out.txt") || die("Error opening out.txt: $!"); print "type your claim:n"; my $string=<STDIN>; for (my $i=1;$i<100;$i++){ print OUT $string; } close OUT; Now let‟s play with <,>,>> and file permissions Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 21. Read from Files Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 22. Read open(IN, “<song.txt”) or die(“Error opening song.txt: $!”); print <IN>; print <IN>; print <IN>; print <IN>; print <IN>; print <IN>; print <IN>; print <IN>; print <IN>; print <IN>; print <IN>; print <IN>; print <IN>; print <IN>; close IN; Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 23. Read with loops Problems: • It‟s long • File size unknown solution: Use loops Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 24. While loop Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 25. While while (condition){ do something… } Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 26. While - for differences While For • Undetermined > Determined • No counter > Counter Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 27. While example Approx. solution of x^2-2=0 (Newton‟s method) my $sol=0.5; my $err=$sol**2-2; while ($err**2>.001){ $sol-=($sol**2-2)/(2*$sol); $err=$sol**2-2; print “X is $solnError=$errn”; } Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 28. Read with while #! /usr/bin/perl -w use strict; open(MOD, "<IG.pdb") || die("Error opening IG.pdb: $!"); while (my $line=<MOD>){ print substr($line,0,6)."n"; } close MOD; Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 29. Redirect outputs Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 30. Redirections #!/usr/bin/perl open(STDOUT, ">foo.out") || die "Can't redirect stdout"; open(STDERR, ">&STDOUT") || die "Can't dup stdout"; select(STDERR); $| = 1; # make unbuffered select(STDOUT); $| = 1; # make unbuffered close(STDOUT); close(STDERR); Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 31. @ARGV Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 32. Command Line Arguments • Command line arguments in Perl are extremely easy. • @ARGV is the array that holds all arguments passed in from the command line. – Example: • % ./prog.pl arg1 arg2 arg3 – @ARGV would contain ('arg1', arg2', 'arg3) • $#ARGV returns the number of command line arguments that have been passed. – Remember $#array is the size of the array -1 ! Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 33. Quick Program with @ARGV • Simple program called log.pl that takes in a number and prints the log base 2 of that number; #!/usr/local/bin/perl -w $log = log($ARGV[0]) / log(2); print “The log base 2 of $ARGV[0] is $log.n”; • Run the program as follows: – % log.pl 8 • This will return the following: – The log base 2 of 8 is 3. Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 34. $_ • Perl default scalar value that is used when a variable is not explicitly specified. • Can be used in – For Loops – File Handling – Regular Expressions Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 35. $_ and For Loops • Example using $_ in a for loop @array = ( “Perl”, “C”, “Java” ); for(@array) { print $_ . “is a language I known”; } – Output : Perl is a language I know. C is a language I know. Java is a language I know. Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 36. $_ and File Handlers • Example in using $_ when reading in a file; while( <> ) { chomp $_; # remove the newline char @array = split/ /, $_; # split the line on white space # and stores data in an array } • Note: – The line read in from the file is automatically store in the default scalar variable $_ Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 37. Opendir, readdir Bioinformatics master course, „11/‟12 Paolo Marcatili
  • 38. Opendir& readdir • Just like open, but for dirs # load all files of the "data/" folder into the @files array opendir(DIR, ”$ARGV[0]"); @files = readdir(DIR); closedir(DIR); # build a unsorted list from the @files array: print "<ul>"; foreach $file (@files) { next if ($file eq "." or $file eq ".."); print "<li><a href="$file">$file</a></li>"; } print "</ul>"; Bioinformatics master course, „11/‟12 Paolo Marcatili