good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
Open Has a New Trickby Zaxo (Archbishop) |
on Oct 02, 2002 at 18:20 UTC ( [id://202343]=perlmeditation: print w/replies, xml ) | Need Help?? |
I was poking around in Perl 5.8.0's core module library, and turned up a new form of open that I hadn't heard about. It happens in lib/5.8.0/{arch}/PerlIO/scalar.pm Something I've occasionally wanted to do is to attach a file handle to a string as an accessor. That has been possible with earlier perl using IO::Scalar or IO::Stringy, but not all filehandle semantics and conventions were honored. I found that that is native in 5.8.0 with PerlIO, and that the syntax is as simple as could be imagined: open FILEHANDLE, MODE, SCALARREF. That's it - give open a reference to the string in the file name slot, and it works. The handle may be read, written, or appended. Globals like $/ work as expected. Here's a sledgehammer-on-peanut example which prints a string in cable-ese (upper case, suppressed spaces, five letter groups):
As an output file:
Append, capturing STDERR:
I've only started to explore this trick. I haven't tried flock or seek/tell or $.. I haven't tinkered with truncate or exotic modes. Here's a challenge. Can you find any limits to file-like behavior? What cool uses can you think of for this? After Compline,
Back to
Meditations
|
|