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

Is there a way to create an IO::File or IO::Handle object that would use a string instead of an actual file?

Reason: I have a tar file in a scalar $string. I'd like to examine its contents using Archive::Tar. However, there are no APIs in Archive::Tar to use a scalar to initialize it, but it can take a filehandle.

  • Comment on Sticking IO::Handle on top of a scalar.

Replies are listed 'Best First'.
Re: Sticking IO::Handle on top of a scalar.
by broquaint (Abbot) on Jan 14, 2004 at 16:36 UTC
    You could use IO::Scalar, or if your perl is 5.8+ then you could take advantage of the ability to open 'filehandles' to scalars e.g
    my $str = ''; open my $fh, '>', \$str; print {$fh} 'this will end up in $str'; print "\$str contains: $str\n"; __output__ $str contains: this will end up in $str
    For more info see. open and IO::Scalar.
    HTH

    _________
    broquaint

    update: reworded first sentence to make sense

Re: Sticking IO::Handle on top of a scalar.
by borisz (Canon) on Jan 14, 2004 at 16:33 UTC
    IO::String does exactly what you want.
    Boris
Re: Sticking IO::Handle on top of a scalar.
by ysth (Canon) on Jan 14, 2004 at 16:47 UTC
    Pre-5.8.0, use IO::Scalar for this. Starting with 5.8.0, you can say just open my $fh, "<", \$string