|Do you know where your variables are?|
FileHandle emulationby gmax (Abbot)
|on Feb 18, 2002 at 06:56 UTC ( #146108=perlquestion: print w/replies, xml )||Need Help??|
gmax has asked for the wisdom of the Perl Monks concerning the following question:
Dear fellow Monks,
I have a parser that is working just fine and uses FileHandle for its input. I need to keep the same functionality, taking input from a string instead of a file.
I thought about writing a separate sub for this purpose, but I realized that a considerable part of my program architecture had to be changed. Therefore I tried another approach, i.e. fooling the application by giving it a handle that behaves like a text file, but has a string underneath.
I couldn't find any ready-to-use solution, and so I came up with my homemade package (see below).
The StringHandle package overloads the angle operator, returning an element of the internal array, which was created by the constructor.
The returned element is removed from the array, thus imitating a sequential file reading.
Also, the code requires that the newline is kept at the end of the returned string, again for compatibility with a file input. On the technical side, the best split pattern that I found was /^/m, which returns a complete string.
A last touch of imitation was the "close" sub, which I would call for a FileHandle object, and should be in my bogus package as well, if I want to avoid an error.
Having this StringHandle package, my script can read from either a file or a string, with the same functionality and no visible problems.
Thus, my requests:
_ _ _ _ (_|| | |(_|>< _|
Back to Seekers of Perl Wisdom