roboticus has asked for the wisdom of the Perl Monks concerning the following question:
Hello, all:
I'm having trouble with a simple script I'm writing, and would appreciate some help. I have several different workarounds (see Note), but none of them feel "right", so I'm looking for alternatives.
Here's the script I'm having trouble with:
#!/usr/bin/perl # # PM_help.pl FileName - Prints contents of file FileName # PM_help.pl -test - Prints contents of <DATA> handle # PM_help.pl - Prints contents of STDIN # use strict; use warnings; use IO::Handle; # Prepare the selected filehandle my $FName=shift; my $FH = new IO::Handle; if (! defined $FName) { $FH->fdopen(fileno(STDIN), "r") or die "Can't grab STDIN!\nErrMsg: $!\n"; } elsif ($FName eq "-test") { # I was hoping one of these two would work, but no luck #$FH->fdopen(fileno(DATA), "r") # or die "Can't grab DATA!\nErrMsg: $!\n"; #$FH->new_from_fd(fileno(DATA), "r") # or die "Can't grab DATA!\nErrMsg: $!\n"; # Works, but I don't care for it open $FH, '<', $0 or die "Can't open '$0'\nErrMsg: $!\n"; while (<$FH>) { last if /^__DATA__\s*$/; } } else { open $FH, '<', $FName or die "Can't open '$FName'\nErrMsg: $!\n"; } # Use the file... while (<$FH>) { print "$.: $_"; } # EXAMPLE DATA __DATA__ The quick red fox jumped over the lazy brown dog. Now is the time for all good men to come to the aid of their party.
The gist of it is, after reading open, perlopentut and IO::Handle, I can't figure out how to grab the <DATA> handle and put it into $FH as I do with the STDIN handle. While I can do it, I feel that there's a better way.
Why do I care?
I usually keep a set of test data with my scripts so I can easily test them, or use them as example input to refresh my memory when I forget the details. But I don't like having to keep track of the data file along with the script when I move it around, pass it to friends, etc. So I'm trying to adopt the practice of putting the test data in the __DATA__ section at the end of the file. Ultimately, I plan on taking the open logic section and putting it into a subroutine that I can place in my ROBO::Utils module.
Note: I've tried:
Thanks in advance!
...roboticus
When your only tool is a hammer, all problems look like your thumb.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Filehandle dilemma (DATA, STDIN, a file)
by BrowserUk (Patriarch) on Mar 11, 2011 at 14:18 UTC | |
by roboticus (Chancellor) on Mar 11, 2011 at 16:45 UTC | |
by BrowserUk (Patriarch) on Mar 11, 2011 at 17:11 UTC | |
|
Re: Filehandle dilemma (DATA, STDIN, a file)
by repellent (Priest) on Mar 12, 2011 at 08:19 UTC |