Tuesday, February 26, 2013

Perl - What is __DATA__ ?



What is __DATA__ ? Why is it used?
    Generally, Perl reads data from a file which in the Perl program can be accessed using open and readline functions. However, for users who just want to test something for an urgent requirement, it is pretty boring to put the test data in a file and access it using the open and readline functions. The solution for this : __DATA__.

   Let us consider a sample text file:
$ cat f1.txt
AIX,1
Solaris,2
Unix,3
Linux,4

1. The common way of reading or processing a file in Perl:
#!/usr/bin/perl
use warnings;
use strict;

open my $fh, '<', 'f1.txt' or die 'Cannot open f1.txt';

while(<$fh>){
        print;
}
close ($fh);
  open function opens the file and associates the file with the filehandler $fh. This file handler with diamond(<> )operator reads a line from the file. Using while loop, the entire file is read and printed till the end of the file is reached. close function closes the file associated with the file handler. This method is little cumbersome in a way that every time to read a file, one needs to have open and close commands.

2.  Using __DATA__ : Input file content in the source file itself:
Let us see how to use this:
#!/usr/bin/perl

use warnings;
use strict;

while(<DATA>){
        print;
}

__DATA__
AIX,1
Solaris,2
Unix,3
Linux,4  
 __DATA__  :
   Any input data to be provided to the Perl program is put below the line __DATA__ . This __DATA__ line indicates that the content following is input file content. Perl automatically attaches the DATA file handler to access this data for the programmer which can then be read  with the diamond operator(<>) . This section should be put only at the very end of the program.
Note: Perl allows to use __END__ as well in place of __DATA__. However, the file handler associated will be DATA itself.

 Reading entire file into an array:
#!/usr/bin/perl

use warnings;
use strict;

my @arr=<DATA>;
print @arr;

__DATA__
AIX,1
Solaris,2
Unix,3
Linux,4
   Just by assigning the DATA handler to an array (for that matter any file handler), the entire file will be read into the array. By loading the entire file into an array, any particular record of a file can be accessed  from the array.

1 comment: