Mar 23, 2013

Reading File in Perl


Let's discuss about reading a file in Perl with an example.

The following code snippet 
1) Checks whether the file (data_read.txt) we are going to read is present or not 
2) Define a file read handle (FILE_READ), it's can be any user defined name
3) Loop through the file handle and read line line from the file
2) Chomp each & every line (to remove the new-line characters (e.g., \n)
4) Print the contents of the file line by line

E.g., 
data_read.txt
Mother Teresa
Nelson Mandela
Abraham Lincoln


file_read.pl

#!/usr/bin/perl

use strict;
use warnings;

my $filename = 'C:\Perl\data_read.txt';

#Check if file is present in the path or not
unless (-e $filename) {
    print "\n File Doesn't Exist!" . $filename;
    exit;


#"FILE_READ" is File Handle
open (FILE_READ, $filename); 

while (my $each_line = <FILE_READ>) {
   
   #"chomp" removes the new lines characters like "\n" at the end of each line 
   chomp $each_line;   
   
   print $each_line . "\n";
}

close (FILE_READ); 



Output:
Mother Teresa
Nelson Mandela
Abraham Lincoln


No comments:

Post a Comment