Sunday, July 24, 2011

To join all the content of the file into a scalar perl


Content of the list.txt:

hello gopal,how are you,
hello james,how are you
hello,how are you,
hello Thomas,how are you,
hello Manjula,how are you,
hello karthik,how are you

Content of the Perl file:

$ddd=getfile("list.txt");
print $ddd;
 sub getfile {
          my $filename = shift;
          local *F;
          open F, "< $filename" or die "Couldn't open `$filename': $!";
          local $/ = undef;           # Read entire file at once
          $contents = <F>;            # Return file as one single `line'
          close F;
          return $contents;
        }

output:


G:\perl_programs>perl perl_filehandle.pl
hello gopal,how are you,
hello james,how are you
hello,how are you,
hello Thomas,how are you,
hello Manjula,how are you,
hello karthik,how are you
G:\perl_programs>

Analysis:
Here the entire content of the file is joined into a scalar by changing the input record separator("$/")  to be undef which is by default to "\n".By using the local scope to the record separator the change is visible only in the subroutine getfile.

No comments:

Post a Comment