my $scalar = "this is my\nstring that I\nwant to read as a file\n";
some_call (FH, "<$scalar");
while(<FH>) { print "$_"; }
What do I put instead of some_call?
The thing is that I have a module that takes a filename. I already have a
file in memory and it seems ridicolous that I must first write the data to
temporary file and read it from disk. I want to rewrite the module so that it
takes a filehandle instead of filename. Then it wouldn't matter whether that
filehandle refers to some string, file on disk, etc..
>Is there a module or a feature in Perl that would allow me to use scalars
>as files? Basically, I want something like this:
>
>my $scalar = "this is my\nstring that I\nwant to read as a file\n";
>some_call (FH, "<$scalar");
>while(<FH>) { print "$_"; }
>
>What do I put instead of some_call?
See IO::String on CPAN.
--
Bart.
> Is there a module...
See FAQ: "What modules and extensions are available for Perl?..."
> ...that would allow me to use scalars as files?
Yes, it has the obvious name and the description "I/O handle to
read/write to a string".
Please do not post "Is there a module...?" questions without looking
first.
> Basically, I want something like this:
>
> my $scalar = "this is my\nstring that I\nwant to read as a file\n";
> some_call (FH, "<$scalar");
> while(<FH>) { print "$_"; }
>
> What do I put instead of some_call?
A 'tie' statement. For details see the documentation of the module.
--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
There are module answers, but since this is crossposted to
comp.lang.perl.misc, I feel I should point out that your
situation can be fixed without making the scalar look like
a file if you want.
my $scalar = "this is my\nstring that I\nwant to read as a file\n";
my @array = split /\n/, $scalar;
for( @array ) { print "$_\n" }
or
my $scalar = "this is my\nstring that I\nwant to read as a file\n";
while( $scalar =~ /(.*?\n)/gs ) { print "$1" }
will do what you want, albeit with different syntax than if you
were using a file. The former would be easiest if you wrote your
intial slurp as
my @array = <File>;
instead of slurping into a scalar then splitting into an array.
Chris
--
Disclaimer: Actual product may not resemble picture in ad in any way.