Tuesday, July 28, 2009

How to read a whole file at a time in perl?

i have to read a file at a time .i should not read a file line by line .it must be read sa a whole file and then i have to apply the commands in the whole file using PERL commands.

How to read a whole file at a time in perl?
Hello,





This idiom is called "slurping". There are a few ways to do it. One is to use the File::Slurp Module [1] on CPAN; however, the code to slurp a file is so minimal I wouldn't bother.





The gist of it is [2]:





open( my $file, '%26lt;', $filename ) or die $!;


my $content = do { local $/; %26lt;$file%26gt; };


close( $file ) or die $!;





The above will read in the entire contents of the file (note, this could be quite memory intensive) into the variable named "$content".
Reply:this way is a little simpler and easier:





$/ = ""; # unset the input line seperator


my $file = %26lt;INPUTFILE%26gt;; # read the whole file at once


$/ = "\n"; # BUT DON'T FORGET TO PUT IT BACK TO NEWLINE!!!


print $file;

garden ridge

No comments:

Post a Comment