Sunday, November 9, 2014

How do you archive files of last week in Perl?

use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
use File::Basename;
use Time::Piece;
use Time::Seconds;

#Get the basename of the script
my $me = $0;
$me =~ s{.*\\}{};

# Calculate DMY for last week w.r.t today
my $lastWeek = Time::Piece->new;
$lastWeek = $lastWeek  - ONE_WEEK;
$lastWeek = $lastWeek->dmy("");

my @temp = ();
my $archive = Archive::Zip->new();

if ($#ARGV != 1) {
print "\nUsage: $me <archive path> <input path>\n";
exit;
}
else {
foreach my $file ( grep { (-M) > 7 } glob("$ARGV[1]/*.*") ) {
print "Adding $file to Archive...\n";
$archive->addFile( $file, basename($file) ) or die "Unable to add \"$file\" to Archive";
push (@temp, $file);
}
     
unless ( $archive->writeToFileNamed("$ARGV[0]/$lastWeek.zip") == AZ_OK ) {
die "Error in creating archive - $!";
}
for (0..$#temp) {
unlink $temp[$_];
}
}

Tuesday, November 4, 2014

How do we find list of directories in a folder in batch file?

@echo off
set basedir=C:\work\perl

set PWD=%cd%
set today=%date:~-4%-%date:~4,2%-%date:~7,2%
if not exist %PWD%\%today% ( mkdir %PWD%\%today% )
dir /s /b /a:d %basedir% > %PWD%\%today%\%today%.ini

How do we handle command line options passed to the program?

use Getopt::Long qw(GetOptions);

my %opts = ();

# Predeclare prototyped subs
sub debug(@);

GetOptions(\%opts,
    'debug!',
);

debug "Success";

sub debug(@){
  if($opts{debug}){
    (my $str=join '',@_)=~s/\s*\z/\n/;
    print $str;
  }
}

Note:
Execute the script as follows:
perl command_line_switch.pl --debug

How do you delete specific files older than 7 days in a directory?

foreach my $dir (@ARGV) {
foreach my $file ( grep { (-M) > 7 } glob("$dir/*.{log,zip}") ) {
print "\nRemoving - $file ...";
unlink $file;
}
}

Note:
It deletes all log/zip files in a directory.

Monday, November 3, 2014

How do you get the delimiter used in CSV file in Perl?

use Text::CSV::Separator qw(get_separator);

my $csv_file = "Test01.csv";

my $delimiter = get_separator( path => "$csv_file",
                                   lucky   => 1,
                                   exclude => [':', ' ', '-'],
                                 );

Monday, October 13, 2014

Create predefined folder & sub-folders on Windows.

@echo off

set PWD=%cd%
set dlist=CLASS01 CLASS02 CLASS03
set slist=PHY CHE BIO GEO MATH

for %%i in ( %dlist% ) do (
   if not exist %PWD%\%%i ( mkdir %PWD%\%%i )
   for %%j in ( %slist% ) do (
       if not exist %PWD%\%%i\%%j ( mkdir %PWD%\%%i\%%j )
   )
)

Rename multi files in a folder on Windows.

@echo off

set count=1
set basedir=C:\old_data\report
for /f "tokens=*" %%G in ('dir /a-d /b %basedir%') do (call :subroutine %%G)
goto :eof

:subroutine
for /F "delims=_" %%a in ("%1") do (
   ren "%basedir%\%1" "%%a_SPRW_Light_%count%.txt"
)
set /a count+=1
goto :eof

Example:
"20141013_Test_Rept.dat" will be renamed to "20141013_SPRW_Light_1.txt"

Write colorful text on console in Perl on Windows.

use Win32::Console;

# get current console attributes
my $console = Win32::Console->new(STD_OUTPUT_HANDLE);
my $cons_attrib = $console->Attr();

$console->Attr($FG_LIGHTGREEN | $BG_BLACK);
print "Hi, Welcome to Arabian Nights";
$console->Attr($cons_attrib); #Restore original attributes

Thursday, September 18, 2014

How do you get timestamp in batch file?

@echo off
set timestamp=%date:~-4%-%date:~4,2%-%date:~7,2%:%time:~0,2%-%time:~3,2%-%time:~6,2%
echo %timestamp%

Friday, August 22, 2014

How do you execute PostgreSQL scripts whose names start with 'p_'?

my $path = 'C:\TestSQL';

my @scripts = `dir /B /s $path`;

foreach my $psqlfile (@scripts) {
   if ( $psqlfile =~ /^(.+\\p\_[^\\]+\.sql)\s*$/i ) {
        `psql -q -h <Hostname> -p <Port> -d <Database> -U <Username> -f $psqlfile.sql -o outputfile`;
   }
}