in reply to Write to and read from scalar

use strict; use warnings; my $str; open my $fOut, '>', \$str; print $fOut "Hello World\n"; close $fOut; open my $fIn, '<', \$str; my $inStr = <$fIn>; close $fIn; print $inStr;

Prints:

Hello World
True laziness is hard work

Replies are listed 'Best First'.
Re^2: Write to and read from scalar
by wwe (Friar) on Mar 23, 2012 at 08:49 UTC
    Hi, I'm not really sure I get the point. This can be done with a simple assignment $variable = 'xyz'. Then you just print this varible with print $variable. If this is not wat you are looking for please try to describe the problem other way.

      The point is that certain functions expect to be passed filehandles for various purposes.

      Sometimes the data you want to pass to these functions is actually held in a variable. The naive way of coping with that is to write out your data to a temporary file, open the file and pass the filehandle to the function. Often a better solution though is to construct a filehandle which points straight to the scalar variable, and not to a real file on disk.

      Grandfather provides one technique, supported by Perl 5.8+. If (for some perverse reason) you want to support earlier releases of Perl, then IO::String also provides a solution using tied filehandles.

      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re^2: Write to and read from scalar
by flexvault (Monsignor) on Mar 23, 2012 at 13:02 UTC

    GrandFather,

    I did it this way from your example. I would not have known how to do this, but the disk file is basically a representation of the scalar.

    my $str = "Hello World\n"; open my $fIn, '<', \$str; my $inStr = <$fIn>; close $fIn; print $inStr;

    Is there a reason to use file I/O to the scalar?

    Thank you

    "Well done is better than well said." - Benjamin Franklin

      For one use reread the OP's node. I frequently use the technique when answering SoPW's where an input file is required. I could write a temporary file then use that, but that adds clutter to the sample.

      In real applications I've used the technique to cache parts of a file that I need to access frequently and to provide a file handle for modules that require them when I really want to pass in a string.

      True laziness is hard work