Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Reading from strings...

2 views
Skip to first unread message

Chaos

unread,
May 31, 2001, 4:15:10 AM5/31/01
to
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?

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..

Bart Lateur

unread,
May 31, 2001, 4:38:53 AM5/31/01
to
Chaos wrote:

>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.

nob...@mail.com

unread,
May 31, 2001, 12:47:36 PM5/31/01
to
mor...@fly.srk.fer.hr (Chaos) writes:

> 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\\

Chris Stith

unread,
Jun 1, 2001, 11:37:10 AM6/1/01
to


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.

0 new messages