Exercise 3 : Reading and writing files
Laboratory Exercise for Introduction to Perl
This assumes you have already set up your initial directory with the init-perllab command (instructions).
Reading from a file (cabeza.pl)
- Change to the Lab3 directory:
cd /scratch/mylogin/PerlLab/Lab3
The directory path may be different if you installed the files in another location. - List the directory contents:
ls -l
You should see the files: INSTRUCTIONS README Solutions cabeza.pl pairs.pl - Look at the cabeza.pl file:
cat cabeza.pl
The contents of this file are as follows (note the line numbers have been added for clarity and are not in the actual file):- #!/usr/bin/perl
- # cabeza.pl - print the first 10 lines of a given file
- use warnings;
- use strict;
- # This is the first argument on the command line
- # Check that file exists and is readable
- unless (-r $filename)
- {
- }
- # Open the file, read up to 10 lines or to the end of file, and
- # output the lines to standard out. This should operate like the
- # unix command "head".
- Edit the cabeza.pl program so it will
open the file specified in the variable $filename,
read up to 10 lines, and output them to standard out.
For example, to print the first 10 lines of the file
"INSTRUCTIONS", it will look like:
command./cabeza.pl INSTRUCTIONS
outputhttp://sc.tamu.edu/shortcourses/SC-perl/lab/ex2/ Exercise 3 : Reading and writing files Laboratory Exercise for Introduction to Perl This assumes you have already set up your initial directory with the init-perllab command.
- For reference, read the perl documentation on
open() or the
tutorial on using open(). You can also view these
from eos by typing:
perldoc -f open
man perlopentut
Writing to a file (pairs.pl)
- Look at the pairs.pl file:
cat pairs.pl
The contents of this file are as follows (note the line numbers have been added for clarity and are not in the actual file):- #!/usr/bin/perl
- # pairs.pl - save a list of numeric pairs to a file
- #
- # Write to the file "squares.dat" a list. Each line
- # will contain a number (i) and the square of that number.
- # The starting and ending number will be specified as user
- # input.
- use warnings;
- use strict;
- my $out_filename = 'squares.dat';
- my ($start, $end);
- $start = <>;
- $end = <>;
- # check that $start <= $end
- # open $out_filename for writing
- # make a loop ($i) from $start to $end
- # write $i and $i*$i to the file
- # close the file
- Edit the program so it will open the file
"squares.dat" and write a line for
each value from the value in $start
to the value in $end. On each line,
print the value and the square of the value. For example,
an input of 3 for start and 11 for end would result in
the file "squares.dat" containing:
output
3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100 11 121
- For reference, read the perl documentation on
open(),
printf(), and
die(). You can also view these
from eos by typing:
perldoc -f open
perldoc -f printf
perldoc -f die