Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 646
wuchang Avatar asked Sep 12 '13 08:09

wuchang


People also ask

How to create file in perl script?

To create a file in Perl, you also use open(). The difference is that you need to prefix the file name with a > character to make Perl open the file for writing. Any existing file with the name you supply to open() will be overwritten, unless you specify >> instead, which opens a file for appending.

How do you open a file for read and write in Perl?

If you want to open a file for reading and writing, you can put a plus sign before the > or < characters. open DATA, "+>file. txt" or die "Couldn't open file file.


2 Answers

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
like image 158
amon Avatar answered Sep 22 '22 19:09

amon


You may want to use OO-style then use IO::String package.

#!/usr/bin/perl

use strict;
use warnings;

use IO::String;

my $s="dfasdfasdfafd....\nabc";
my $io = IO::String->new($s);

while (my $line = $io->getline()) {
   print $line;
}

print "\nTHE END\n";

# write new line
$io->print("\nappend new line");

# back to the start
$io->seek(0, 0);

while ($io->sysread(my $line, 512)) {
   print $line;
}

Also you may use almost all methods described in IO::Handle package.

This solution is useful when some of another package accepts only IO::Handle (IO::File) object to manipulate data.

like image 40
gh0stwizard Avatar answered Sep 23 '22 19:09

gh0stwizard