| Developer's Daily | Perl Education |
| front page | java | perl | unix | dev directory | web log |
Introduction
The other day I was working on a Windows95 laptop, and I really missed
my good friend, the Unix cat command. I was trying to merge
a bunch of files together, and couldn't think of how to do it easily on
Windows system (the DOS type command certainly didn't do it).
Easily distracted, I set off to write a cat command with
Perl that I could use on any system.
A little background - how cat should work
For those who are not familiar with Unix, the cat command stands for concatenate. You can use cat to display the contents of a file named myfile by typing:
First, a little algorithm
In this first article, we'll keep it simple. Our algorithm will work like this:
Show me the code!
Without any further ado, Listing 1 shows what these steps look like in Perl code:
|
#!/usr/bin/perl -w
# for each arg, open the file and print it FILE: foreach (@ARGV) { open(FILE, $_) || ((warn "Can't open file $_\n"), next FILE); while (<FILE>) {
|
| Listing 1: | Our simple "cat" program opens each
file in succession, and prints the file contents. A warning message
is printed to STDERR if a problem occurred trying to open a file.
|
Quick discussion
The only thing I've done here that's very tricky is (a) the use of the warn statement and (b) the FILE label. The warn function just prints my message out to STDERR, but unlike the die function, the program goes on. If a user wants to cat out four files, for example, and the second file doesn't work for some reason, I don't want the program to come to a complete stop. I'd rather just put an error message on STDERR and keep working on the rest of the files.
I use the FILE label as a reference for the next
statement. I use it because I think it makes the program easier
to read, which is helpful when I come back to look at this program some
time in the future. I've seen other people that really don't like to use
these types of labels, but in my opinion, I think the code is
easier to read.
Running the cat program
Assuming you wanted to open three files named moe, larry, and curly, you would run the program on a Unix system like this:
That's it, that's all
As usual with Perl, There's More Than One Way To Do It. This was just the first approach that came to mind, and I think it reads well. We're always open to suggestions, though, so if you think you have a better way to do it, write us a quick note. We'll incorporate your thoughts with this article as quickly as we're able.
Best wishes!
Copyright © 1998 DevDaily Interactive, Inc.
All Rights Reserved.