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

ε祈祈猫儿з 提交于 2019-12-23 12:17:58

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/18759597/how-can-i-convert-a-string-to-a-file-handle-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!