Perl-Sensitive Sunglasses | |
PerlMonks |
Re: Pre-empting STDIN during Testingby Revelation (Deacon) |
on Feb 15, 2005 at 01:38 UTC ( [id://431004]=note: print w/replies, xml ) | Need Help?? |
The easiest way to do this is to use IO::Handle:
You'll notice that this (at the least) solves your problem with the diamond operator. With regards to a while (<>) loop, for which I assume, you have a last() somewhere, the solution is not as clear. Obviously, any file has a limited length. Perhaps, there's some way to use IO::Handle as a base and generate some sort of callback routine that could generate more data, but that's a little too dirty for me. Realistically, are you going to need more than, say, 2,000 lines? If not, then just create a 2,000 line file. What's nice about this approach is that IO::Handle handles reverting STDIN to its previous state, after $fh->close for you. Moreover, it's also a rather simple approach. However, in addition, you could also always localize STDIN, like so: Both of these aproaches will work whether you're calling STDIN in a used module or in the test script, itself. However, I assume each approach has different limitations as to backwards compatibility which I have not explored as of yet. P.S: FYI, this is technique is generally called 'overloading STDIN'. Your searches would have been more successful, even on perlmonks, if you had used the proper vocabulary. :) Update: With regards to your specific question, here's a possible (untested--closer to pseudocode) solution, which mimics your own (in functionality.) Moreover, and the true beauty of IO::Handle, is that you can inherit from it. If you want to have a retrieve values from a list, rather than using my silly workaround, then feel free to write a module inheriting from IO::Handle that does so (my advice would be to overload perhaps fdopen and definitely getline and getlines)! Otherwise, IO::Handle _at least_ gives you a template for extending Perl's IO system in a more flexible manner than tying a hash. Perhaps, another monk will have an in-the-box workaround on IO::Handle to allow you to use a callback to a subroutine that shifts from an array (look at IO::String to see how this is handled for strings--you could modify that), but until then, you now have a pretty flexible solution that only involves a temporary file (which can be created using IO::File); I'm going to sleep now, but perhaps tomorrow, I'll think of a better solution, or somebody smarter than myself, like merlyn will do so. Gyan Kapur The Worst Nodes Upvoter!
In Section
Seekers of Perl Wisdom
|
|