Regular expression in Perl (how to replace a date string)

Posted by Faiz on February 1st, 2009 filed in Perl Support

In Perl you can replace a string easily, than your normal counterpart SED editor. With SED you would have to use the -e flag in order to edit the content of your data - then pipe it to a new output file and then finally rename the new output file the appropriate file name again. With Perl this becomes simple to do. All you do is use the Perl -i flag this is a Perl internal that will automatically create a backup of the original file you - all you do is give the backup file name extension. Look at my scripts first line.

Since this is hard coded routine, I have made the variables local to my routine followed by . Finally the reason behind my madness is simple, with Perl your code is portable i.e. I can execute this code on any machine with a Perl compile. Well that’s not 100% true, if I compile this code into a standalone binary I can run the exe on any machine. To do this download Active states perl2exe (this is not freeware) or use Cava Packager this is completely free. Once you compile this code you can distribute it (you got the option to compile it into an auto installer) and any user can run it on windows system without even having Perl locally on their machine. So with Perl you code really becomes portable no more coding for a specific Unix distribution or Windows flavor.
Code below!!!!!
============

#!/usr/bin/perl -i.bkup

use strict;
use warnings;

system(’clear’);

#Declare + Initialization;
#=========================

my $replace_OLD=’2008/02/03′;
my $replace_NEW=’2009/01/20′;
my $num_of_args = @ARGV;

# Print the usage out !!!!
#=========================

print “nnComment: Number of arguments is: $num_of_argsn”;

# Verify number of arguments if zero just exit!!!!
#=================================================

if ($num_of_args == 0)

{ print “nnERROR: No command line arguments passed to the script $0 n”;

print “USAGE: n”;
print ‘Example 1 : ./Replace_Dates.pl inputfile’,”n”;
print ‘Example 2 : ./Replace_Dates.pl /dsk1_app/sys1/*.DAT’,”n”;

exit;
}# END_if

# Now loop through those records !!!!
#=====================================

while () #Start reading in Data
{
s/$replace_OLD/$replace_NEW/g;
print;
} # END_while

print “nDONE. Script: $0n”;

Comments are closed.