Connecting Tech Pros Worldwide Forums | Help | Site Map

reading file into string

Member
 
Join Date: Jul 2007
Posts: 35
#1: Aug 20 '08
Hi ,
i have file of 32kb , i want to read the whole file into string ,
i tried this by doing the below code, but i dint got the whole content of the file in the string , i guess the variable is not able to hold the all data, is there any way where i can achive the same?

Expand|Select|Wrap|Line Numbers
  1. open(FH, "$file");
  2.     my @output = <FH>;
  3.     close FH;
  4. foreach $logmsg (@output)
  5.     {
  6.         $sdpString = "$sdpString" ."$logmsg";
  7.  
  8.     }
  9.  

KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#2: Aug 20 '08

re: reading file into string


Expand|Select|Wrap|Line Numbers
  1. open(FH, $file) or die "$!";
  2. my $sdpString = do{local $/; <FH>;};
  3. close FH;
  4. print $sdpString;
  5.  
chaosprime's Avatar
Newbie
 
Join Date: Aug 2008
Location: New Jersey
Posts: 5
#3: Aug 20 '08

re: reading file into string


I typically do like so:
Expand|Select|Wrap|Line Numbers
  1.       open(FH, $file) or die "$!";
  2.       my $sdpString = join('', <FH>);
  3.       close FH;
  4.       print $sdpString;
  5.  
I do want to say, though, that if it's in any way feasible for you to do whatever operation you're doing on one line of the file at a time, you ought to try doing it that way. The structure of Perl encourages you to do things one-line-at-a-time because it's a good idea.
KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#4: Aug 20 '08

re: reading file into string


Quote:

Originally Posted by chaosprime

I typically do like so:

Expand|Select|Wrap|Line Numbers
  1.       open(FH, $file) or die "$!";
  2.       my $sdpString = join('', <FH>);
  3.       close FH;
  4.       print $sdpString;
  5.  
I do want to say, though, that if it's in any way feasible for you to do whatever operation you're doing on one line of the file at a time, you ought to try doing it that way. The structure of Perl encourages you to do things one-line-at-a-time because it's a good idea.

Do it the way I show above, much more effcient than using join(), but if its a small file it won't matter much.
Reply