homepage Welcome to WebmasterWorld Guest from 54.205.254.108
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / Perl Server Side CGI Scripting
Forum Library, Charter, Moderators: coopster & jatar k & phranque

Perl Server Side CGI Scripting Forum

    
Assign contents of file to a scalar variable
SlowMove




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

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




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

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




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

Thanks for the help.

moltar




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

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

dkubb




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

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




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

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


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

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / Perl Server Side CGI Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved