Home arrow Perl Programming arrow Page 5 - Perl 101 (Part 4) - Mind Games

Die! Die! Die! - Perl

This week's article teaches you how to use Perl to interact withfiles on your system, and also provides you with a quick crash course invarious array functions.

  1. Perl 101 (Part 4) - Mind Games
  2. Handle With Care
  3. Different Strokes
  4. A Little Brainwashing
  5. Die! Die! Die!
  6. Testing Times
  7. Popguns And Pushpins
  8. Shifting Things Around
  9. The Real World
  10. Miscellaneous Stuff
By: Vikram Vaswani and Harish Kamath, (c) Melonfire
Rating: starstarstarstarstar / 11
June 29, 2000

print this article


It's strange but true - an incorrectly opened file handle in Perl fails to generate any warnings at all. So, if you specify a file read, but the file doesn't exist, the file handle will remain empty and you'll be left scratching your head and wondering why you're not getting the output you expected. And so, in this section, we'll be showing you how to trap such an error and generate an appropriate warning.

Let's go back to our first example and add a line of code:
# open file and define a handle for it
open(MIND,"thoughts.txt") || die "Unable to open file!\n";
# print data from handle
print <MIND>;
# close file when done
# display message when done
print "Done!\n";

The die() function above is frequently used in situations which require the program to exit when it encounters a fatal error - in this case, if it's unable to find the required file.

If you ran this program yourself after removing the file "thoughts.txt", this is what you would see:
Unable to open file!

Obviously, this works even when writing to a file:
# open file for writing
open(BRAINWASH,">wash.txt") || die "Cannot write to file!\n";
# print some data to it
print BRAINWASH "You will leave your home and family, sign over all your
money to me, and come to live with forty-six other slaves in a tent until I
decide otherwise. You will obey my every whim. You will address me as The
Great One, or informally as Your Greatness.\n";
# close file when done
close (BRAINWASH);

This article copyright Melonfire 2000. All rights reserved.

>>> More Perl Programming Articles          >>> More By Vikram Vaswani and Harish Kamath, (c) Melonfire

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: