Simple I/O

This section shows you how to do simple I/O. In Chapter 9, “Advanced I/O,” you learn how to do more complex I/O. In this section, you learn how to read and write files, thus unlocking a whole new set of programming possibilities.

Reading Files

To open a file for reading, use the open function. For example, to open the file data.txt use the statement

open IN_FILE, "<data.txt";

This statement opens a file named data.txt for reading and associates it with the file variable IN_FILE. The “<” is a special character that indicates that you want to read this file.

The open function returns true if the open worked, and undef if it did not.

You can check the result using an if statement:

 if (not (open IN_FILE, "<data.txt")) { print "Error: ...

Get Perl for C Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.