Welcome to WebmasterWorld Guest from 54.163.35.238

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

Assign contents of file to a scalar variable

     

SlowMove

11:48 pm on Jan 31, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've got the following code to assign the contents of a file to an array:


open FILE, "inputfile" or die "Couldn't open file";
@lines=<FILE>
close FILE;

Does anyone know how to assign the entire contents of a file to a scalar variable?

sugarkane

12:23 am on Feb 1, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



open FILE, "inputfile" or die "Couldn't open file";
$content.=<FILE>
close FILE;

...will do the trick.

The important part is the .= in the line $content.=<FILE> , which means the next line of the file is appended to $content rather than $content being set to each line in turn.

SlowMove

9:11 pm on Feb 1, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks for the help.

moltar

10:01 pm on Feb 1, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



local (*HANDLE, $/, $_);
open(HANDLE, '< file.txt') or die $!;
my $string = <HANDLE>;
close(HANDLE);

dkubb

4:18 am on Feb 2, 2004 (gmt 0)

10+ Year Member



Here's my favorite way to "slurp" a file into a scalar:

open FILE, 'inputfile' or die "Could not open file inputfile: $!";
sysread(FILE, my $content, -s FILE);
close FILE or die "Could not close file: $!";

SlowMove

4:25 am on Feb 2, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I apprecitate all the help. I wound up using some code I found searching usenet. It's really fast.


{ local $/; $content = <HANDLE> }
 

Featured Threads

Hot Threads This Week

Hot Threads This Month