monkfan has asked for the wisdom of the Perl Monks concerning the following question:

Dear revered monks,

Is there a way to do it? Module for it? Suppose I have this large string.
my $string = 'foo bar qux woo etc etc';
I would like to convert that string as if it is stored inside a file, and bypassing the file creation step.
my $filehandle = do_sth_to_convert($string);
Such that I can straight away do things like:
while (<$file_handle>) { print; }

Regards,
Edward

Replies are listed 'Best First'.
Re: Converting a String to a FileHandle
by japhy (Canon) on May 22, 2006 at 03:00 UTC
    Perl 5.8 can do this with open():
    open my $fh, "<", \$string or die "can't read from \$string: $!"; while (<$fh>) { ... }
    You're opening a reference to a scalar to read from.

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: Converting a String to a FileHandle
by GrandFather (Saint) on May 22, 2006 at 02:48 UTC

    See IO::String.

    use warnings; use strict; use IO::String; my $io = IO::String->new ("This is some text\nto be processed as\na fi +le"); print while <$io>;

    Prints:

    This is some text to be processed as a file

    DWIM is Perl's answer to Gödel
Re: Converting a String to a FileHandle
by bobf (Monsignor) on May 22, 2006 at 03:16 UTC

    Here is an example from the docs for IO::Scalar:

    ### Open a handle on a string, read it line-by-line, then close it +: $SH = new IO::Scalar \$data; while (defined($_ = $SH->getline)) { print "Got line: $_"; } $SH->close;

    I know you were looking for an approach that uses or acts like a filehandle, but here is something that uses split instead:

    use warnings; use strict; my $string = "This is some text\nto be processed as\na file"; # use a zero-width positive look-behind assertion to split # the string on whatever is used as the input record # separator ($/) without consuming it foreach my $line ( split( m[(?<=$/)], $string ) ) { print $line; } # or, if you prefer the one-liner look print for split ( m[(?<=$/)], $string );

    Update: Added the alternate form of the for/split loop.