2
Agenda
> Perl IO> Open a File> Write on Files> Read from Files> While loop
Paolo Marcatili - Programmazione 08-09
4
Why IO?
Since now, Perl is
#! /usr/bin/perl -wuse strict; <- ALWAYYYYYSSSS!!!my $string="I love tomatoes!\n";for (my $i=1;$i<100;$i++){ print $string;}
Paolo Marcatili - Programmazione 08-09
5
Why IO?
But if we want to do the samewith a user-submitted string?
Paolo Marcatili - Programmazione 08-09
6
Why IO?
But if we want to do the samewith a user-submitted string?
IO can do this!
Paolo Marcatili - Programmazione 08-09
7
IO types
Paolo Marcatili - Programmazione 08-09
Main Inputs> Keyboard> File> ErrorsMain outputs> Display> File
8
More than tomatoes
Let’s try it:
#! /usr/bin/perl -wuse strict; my $string=<STDIN>;for (my$i=1;$i<100;$i++){print $string;}
Paolo Marcatili - Programmazione 08-09
9
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”
Paolo Marcatili - Programmazione 08-09
10
Handles
Handles are just streams “nicknames”Some of them are fixed:STDIN <-default is keyboardSTDOUT <-default is displaySTDERR <-default is displaySome are user defined (files)
Paolo Marcatili - Programmazione 08-09
12
open
We have to create a handle for our fileopen(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
Paolo Marcatili - Programmazione 08-09
13
close
When finished we have to close it:close OUT;
If you dont, Santa will bring no gift.
Paolo Marcatili - Programmazione 08-09
14
Print OUT
#! /usr/bin/perl -wuse 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
Paolo Marcatili - Programmazione 08-09
16
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;
Paolo Marcatili - Programmazione 08-09
17
Read with loops
Problems:> It’s long> File size unknown
solution:Use loops
Paolo Marcatili - Programmazione 08-09
20
While - for differences
While
> Undetermined> No counter
Paolo Marcatili - Programmazione 08-09
For
> Determined> Counter
21
While example
Approx. solution of x^2-2=0
my $err=1;my $sol=0;while ($err>.1){$sol+=.0001;$err=$sol**2-2;}
Paolo Marcatili - Programmazione 08-09
22
Read with while
#! /usr/bin/perl -wuse strict;open(MOD, "<IG.pdb") || die("Error opening
IG.pdb: $!");
while (my $line=<MOD>){ print substr($line,0,6)."\n";}close MOD;
Paolo Marcatili - Programmazione 08-09