Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

text file as a string 3

Status
Not open for further replies.

ailse

Programmer
Jan 20, 2004
79
GB
I have a text file of one very long string - once i've opened the filed for reading how do i declare the string inside as one string variable?

in this sort of syntax...

open (FILE, "filename.txt")

my $stringvariable = all the text in the file

while (<FILE>) {
#### operations on the string
}



 
Try this....

open (FILE, &quot;filename.txt&quot;)

my @stringvariable = FILE;

$stringvariable = join ('\n', @stringvariable);


 
if you want to read an entire file - including hard returns - into a scalar then do this:-

$/ = undef;
open (FILE, &quot;filename.txt&quot;);
my $stringvariable = <FILE>;
close FILE;


the $/ is the input record separator. undefining it causes stops the input ceasing once it hits a new line


Kind Regards
Duncan
 
yang yang

there were a couple of errors in your script:-

open (FILE, &quot;filename.txt&quot;)[red];[/red]
my @stringvariable = [red]<[/red]FILE[red]>[/red];
$stringvariable = join ('\n', @stringvariable);


Kind Regards
Duncan
 
Code:
open(FILE, &quot;filename.txt&quot;);
$stringvariable = join(' ', <FILE>);
close(FILE);

is another way to do it.
 
duncdude, I have used your code as follows:

#!/usr/bin/perl

use strict;
use warnings;

$/ = undef
open(TEST, &quot;test.txt&quot;);
my $str = <TEST>

print $str;

but I get a coulple of errors when I try to do this:

&quot;unrecognised escape \p passed through test.pl&quot;
&quot;readline on closed filehandle TEST at test.pl&quot;

any ideas on what I'm doing wrong?

thanks,

Sirisha :)
 
You're missing a couple of semicolons.

[tt]$/ = undef;[/tt]
and
[tt]my $str = <TEST>;[/tt]
 
rosenk -

sorry yes I didn't mean to post that version of the code - the errrors occur even with the semicolons in place...

 
I'm using activeperl v.5.8.2 if that makes any difference?
 
Alright, just a stupid mistake on my part - all sorted now! I had the filename written with &quot;\&quot; instead of &quot;/&quot;.. d'oh!


thanks for all the help though :)
 
yangyang, I should point out that your code is not very efficient memory-wise, as the contents of the file are now stored twice, in $stringvariable and @stringvariable.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top