in reply to How do I treat a string like a filehandle?

Just did this in a real app - nearly fell out of the chair when it worked.
require 5.8.0; ## in order to write NSANS format to a scalar use strict; foreach $ns_answer (@ns_answer) { open(NSANS,">", \$ns_holder) or die("bla..\n"); write NSANS; print OFILE $ns_holder; close(NSANS); } format OFILE= ## for the disk file report @<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< +<<<<<<<<<<<<< $adr, $ptr_answer . format NSANS= ## written to handle, then to scalar, then printed t +o OFILE @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< +<<<<<<<<<<<<< $ns_answer .
To clarify, the format NSANS was defined, but when used, the scalar $ns_holder is opened to write to. Once the write is done, the scalar $ns_holder contains the NSANS-formatted structure.

Then the scalar $ns_holder can be written ("print"ed) to another handle, in this case the format OFILE (the final output file).. so a format(ed) thing containing different scalars can get written to a previously defined and already open'ed file handle (two identical output formats, containing different scalars, written to a single output file handle).

That wasn't too clear - sorry - but I hope it's evident that you can write to a handle to a scalar.

Replies are listed 'Best First'.
Re: Answer: How do I treat a string like a filehandle?
by zentara (Cardinal) on Mar 09, 2004 at 15:59 UTC
    And if you are using a pre-5.80 level, or just want to be backward compatible, you can use IO::Scalar
    #!/usr/bin/perl #You could use IO::Scalar which seems to #be part of IO::Stringy. use IO::Scalar; $data = "My message:\n"; ### Open a handle on a string, and append to it: $SH = new IO::Scalar \$data; print $SH "Hello"; print $SH ", world!\nBye now!\n"; print "The string is now: ", $data, "\n"; ### Open a handle on a string, read it line-by-line, then close it: $SH = new IO::Scalar \$data; while (<$SH>) { print "Got line: $_"; } close $SH;

    I'm not really a human, but I play one on earth. flash japh