Reading and Writing FilesOne of Perl's mottos is:
Hard Things Possible.
In some languages even easy things are hard.
Text files are ubiquitous - they are the 'lingua franca' of the cyber world. Configuration files, HTML, Postscript, RTF, program source files, XML, email. All of these are text files. Reading and writing them should be easy. 78-82 179-191 99-102
Reading FilesWith your favorite text editor create file of names:Here is a Perl program to read that file:names.txt ------- Art Bob Zoe Christian Sabrina Marge It reads the first line and prints:open NAMEIN, "names.txt"; $line = <NAMEIN>; print "hello, $line"; close NAMEIN; The name "NAMEIN" is called a file handle. It is conventionally in UPPER CASE.hello, Art To read all lines:
Note that we are making an assignment to $line within the boolean
of the while. This is okay. The value of an assignment
is the value that was assigned.
The loop will terminate when the end of the file is reached. At this point $line will be assigned 'undef' which is false.
If the file "names.txt" may not exist you need to watch for that:
The function 'exit' will immediately exit the program.
Nothing else will happen.
The function 'die' prints an error message and then exits.
So equivalently we have:
The usual, more concise, and fun way of writing this is: If you are curious WHY it could not open the file you can do this:open NAMEIN, "names.txt" or die "cannot open names.txt\n"; $! contains the error message from the last system command that failed. The mnemonic for this is "What Went Bang?". :)die "cannot open names.txt: $!\n"; $! is a rather cryptic variable name but it is one of many that are commonly used in Perl so you might as well start getting used to them! Other common ones are $_, @_, $/, $|, $&. They all have some clever mnemonic. Writing FilesTo CREATE a text file:
Note the ">" as the first character of the
second parameter to open. This causes the
file to be created (it is truncated if already exists)
and opened for writing.
Note that the same built-in function 'print' is used to print to the standard output (the terminal screen) and to print to files. This is nice but may be confusing. The difference is that when printing to a file you put a filehandle directly after 'print'. It is important that you do NOT put a COMMA (,) after the filehandle in the print statement. See above. There is no comma after the 'OUT'. When opening a file for output the file will be overwritten and truncated if it already exists. If you want to add to the end of the file rather than starting all over again you can do this: This opens the file for appending. See the ">>" instead of ">".open OUT, ">>data.txt" or die "could not append to data.txt: $!\n"; Exercises
|