Search code examples
stringperlfilehandle

How can I convert a string to a file handle in perl?


I have a very big-size string $s="dfasdfasdfafd....", of nearly 1,000,000 characters. I want to convert it to a file handle, making it look like this string is read from a file. But I don't want to store it to a temp file and read it.

Can anyone give me some suggestions?


Solution

  • Open a reference to a string:

    use strict; use warnings; use autodie;
    
    my $foo = "abc\ndef\n";
    open my $fh, "<", \$foo;
    
    while (<$fh>) {
      print "line $.: $_";
    }
    

    Output:

    line 1: abc
    line 2: def