reading file into string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jain236
    New Member
    • Jul 2007
    • 36

    reading file into string

    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?

    Code:
    open(FH, "$file");
    	my @output = <FH>;
    	close FH;
    foreach $logmsg (@output)
    	{
    		$sdpString = "$sdpString" ."$logmsg";
    		
    	}
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    Code:
    open(FH, $file) or die "$!";
    my $sdpString = do{local $/; <FH>;};
    close FH;
    print $sdpString;

    Comment

    • chaosprime
      New Member
      • Aug 2008
      • 5

      #3
      I typically do like so:
      Code:
            open(FH, $file) or die "$!";
            my $sdpString = join('', <FH>);
            close FH;
            print $sdpString;
      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.

      Comment

      • KevinADC
        Recognized Expert Specialist
        • Jan 2007
        • 4092

        #4
        Originally posted by chaosprime
        I typically do like so:
        Code:
              open(FH, $file) or die "$!";
              my $sdpString = join('', <FH>);
              close FH;
              print $sdpString;
        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.

        Comment

        Working...