Friday, May 11, 2012

Convert Comma-Delimited File to Pipe-Delimited File

#!/usr/bin/perl

use File::Basename qw(basename);

$me = basename ($0);

if ( $#ARGV < 0 )
{
 print "Usage : $me <CSV File Name>\n";
 exit;
}

my $IN_CSV = shift @ARGV;
my $OUT_PIPE = $IN_CSV;
$OUT_PIPE=~s/\.csv/\.txt/g;


open (OUTPUT, ">$OUT_PIPE") || die "Can not open $OUT_PIPE - $!" ;
open (INPUT, "<$IN_CSV") || die "Can not open $IN_CSV - $!" ;

while (<INPUT>)
{
 $_=~ s/\,/\|/g;
 print OUTPUT $_;
}

close INPUT;
close OUTPUT;

What is "Here-Document"?


The Unix shell has got a facility "here-document" which allows you to put input under a command, instead of in a separate text file and feed it into the program.
This is done by placing a "<<" and a character string after the command.  Then, every line after the command is interpreting as free-form text to be fed into the command, until a line is hit that has the character string.
For example,
cat <<!
This is an example of text taken literally except that variables are expanded where their variable names appear.
!
would behave exactly like
cat < file
where the file would contain:
This is an example of text taken literally except that variables are expanded where their variable names appear.

Thursday, May 10, 2012

What is the difference between "Print 'Hi $First_Name';" and "Print "Hi $First_Name";"?

The first statement in single quotes will be treated as a constatnt string. The value assigned to the variable would not be the outcome. Rather the output would be :

Hi $First_Name

On the other hand, the second statement would replace the variable with the actual value and the output would be :

Hi <Value Assigned to the variable>