Tuesday, 5 April 2016

Perl – File Read Write Example

Perl – File Read Write Example


In this post, let’s see how to remove the new line character or line break in a text file and save the result in another text file.

Refer to other posts File handling, RegEx.

To accomplish the removal of new line character, we use RegEx substitution operator. The code for substitution is as below,
    $a =~ s/\n//;   # $a is the variable in which the replacement takes place


·         The input to the script is through command line arguments. The command line inputs are stored in the array variable @ARGV (please note the CAPS). First we check the size. If no command line arguments is specified, the size of ARGV is -1. If so, the script prints the usage & exits, using the in-built function die().

unless($#ARGV <0) {
    $in_file=$ARGV[0];
} else {
    die "\nUsage:\n remove_new_line.pl <input_file>\n";
}


·         If valid input is provided, then open the specified file in read mode as below. If unable to open the file, exit with a note printed.  $! Is the Perl system variable which prints the error from the OS.
  open FIN, "<$in_file" or die "Unable to read '$in_file' :$!";


·         Create the output file by appending the name “new_” to the input file name.
open FOUT, ">new_$in_file" or die "Unable to create 'new_$in_file' :$!";


·         Then create a loop, that executes for each line of the input file. Then remove the newline character and write back the result to output file.
while ($a=<FIN>) {
  # remove \n character
    $a =~ s/\n//;
  # write the new data to text file
    print FOUT $a;
 }

Sample output of this script:
            Top file is the input & bottom file is the output.







0 comments:

Post a Comment

Search Here...