Tuesday, December 21, 2010

File I/O In Perl

Reading File:
To read a file, you need a handle:
>> open(my $in, "<", "D://data.txt") or die "Cannot open file: $!";

Then you use:
>> my $line = <$in>;    # just per line
>> print $line;
>> my @lines = <$in>;   # whole documents
>> print @lines;

Or you can read to whole of the text use:
>> while(<$in>){
>>     print "Text: $_";
>> }

Writing To File:
Firstly, create file handle:
>> open(my $out, ">", "D://test.txt") or die "Can't open: $!";

Then write to your file:
>> $msg = "Hello. Hope this file\nGot in the text so we can",
          "happy use it";
>> print $out $msg;

No comments:

Post a Comment