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

How to Open 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



Before you can read the script, you have to open it. Unless you are Superman and have X-ray vision. And even then you might want to lay off the x-ray vision; get it mixed up with your laser eye beams and you can say good-by to that Super Hero pension check.

The syntax for opening a file is: open(HANDLE, “FileName/Location”); Since we are saving our file and script in the same directory, we don't need to worry about location in this instance. Handle is used to reference the file when you read it and close it. Here is a sample of how it should look:

open(PLOT, “super.txt”);

You can also store the file name as a variable if you like, so that you can change it more easily in the future:


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

The above code does several things. First, it creates a variable named $my_file and adds the value “super text” to it. Then we open the file, referencing it with the newly created variable. Lastly, I added an OR to the program, that states either load the program, OR create a pop-up alert that tells the user: I refuse to open your file! We do this to alert the user in case there is a problem opening the file.

>>> 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: