Home arrow Perl Programming arrow Page 3 - Perl: Working with Files

How to Read a File - Perl

In our last series of tutorials we worked with Conditionals and Loops to create some basic Perl programs. This time around we are going to be working with files. Text files, CGI files, PL files, boiled files, fried files, Files Benedict, steamed Files. Okay, so I was kidding about the steamed Files.

  1. Perl: Working with Files
  2. How to Open a File
  3. How to Read a File
  4. Manipulating Data
  5. How the Code Works
By: James Payne
Rating: starstarstarstarstar / 8
November 07, 2007

print this article



Now that we have opened our file, we can read from it. One way to do this is to assign the data within the file to an array. Behold!


open(PLOT, $my_file) || die(I refuse to open your file!);


In the example above, we again create a variable named $my_file and store the name of our file within it (super.txt). Next, we open the file using the word PLOT as our Handle, and using the newly created variable. We add the OR and the DIE command in case the file encounters a problem while loading. Lastly, we create an array named @my_data to store the data of our file, super.txt. Note that we reference our file with the PLOT handle.

How to Close a File

After we read the data we will want to close the file. To do so, we simply add close(Plot); to our code, like so:


open(PLOT, $my_file) || die(I refuse to open your file!);



I know what you are thinking: that sure was easy. Well don't get too cocky you slacker. We still haven't learned how to work with that data yet.

>>> More Perl Programming Articles          >>> More By James Payne

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: