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`;
   }
}

How do you execute all sql files in a directory?

my $path = 'C:\TestSQL';

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

foreach my $sqlfile (@scripts) {
   if ( $sqlfile =~ /^(.+\.sql)\s*$/i ) {
       `mysql <db_name> -u <user_name> -p <password> < $sqlfile.sql`;
   }
}

Wednesday, August 20, 2014

How do you add path of perl to environment variable on command prompt?

1. Open "cmd.exe" with Administrator Privilege (on right click on app) and type the command below.
     setx path "%path%;C:\Perl64\bin;"
2. Restart "cmd.exe".

Monday, July 7, 2014

Move N number of files from one directory to other.

@echo off

set Source=C:\PerlDrift_Bat\IN
set Target=C:\Perl\Drift_Bat\OUT

set MaxLimit=20

for /f "tokens=1* delims=[]" %%G in ('dir /A-D /B "%Source%\*.*" ^| find /v /n ""') do (
move /y "%Source%\%%~nxH" "%Target%"
if %%G==%MaxLimit% exit /b 0
)

Sunday, June 8, 2014

How do you count number of lines in a file?

my $msg;

open(IN, "<", "$0") or die "Can't open $0 - $!";
while (<IN>) {
$msg = $msg . $_;
}
close IN;

$count = () = $msg =~ /\n/g;
print "Line Count - $count\n";

#or

$lines = () = $msg =~ m/\n/g;
print "Line Count - $lines\n";

How do you replace either of the words with a new word?

if ($line =~ m/O(RC|BR)/) {
$line =~ s/$&/\n\n$&/ig;
}

will replace either ORC or OBR with "\n\nORC" or "\n\nOBR".

Friday, May 16, 2014

How can you detect comment or blank line in a file?

open (FH, "$File") || die "Can't open $File - $!\n";
while (<FH>) {
    chomp;
    if ($_ =~ /^(#|;|$)/) {
        print "Found Blank-Line or Commented-Line @ line - #$.\n";
    }
}
close (FH);

Friday, April 18, 2014

How do you create a log file with the name that of script?

require 'Date'
require 'Fileutils'
require 'Logger'

$today = Date.today.strftime("%Y%m%d")
$log = Logger.new("#{File.basename($0, '.*')}.#$today.log", 'daily')

How do you create a log file with name that of batch script?

@echo off
set me=%~n0
set list=Error Log Admin
for %%i in ( %list% ) do (
   if not exist %%i ( mkdir %%i 2>%me%_error.log )
)

Thursday, April 17, 2014

Monday, April 14, 2014

How can you install a list of modules if already not there?

my @module = ('Text::CSV::Separator 0.20',
                       'Getopt::Lucid',
                          'Apache::Htpasswd',
                          'IO::CaptureOutput',
 );
for(@module) {
  eval;
if($@) {
$_=~/\w+\W(\S+)/;
print "Module $1 does not exist! Trying to install it.\n";
system("ppm", "install", "$_");
}
else {
print "Module $_ exists!\n";
}
}

Wednesday, April 2, 2014

How do you evaluate expressions in situ in ruby?

The evaluation of embedded expressions can be achieved using "#{}".
e.g, "abcd #{5*3} efg"

How can you add command prompt or power shell to context (Right Click) menu in Windows?

Create a ".reg" file containing the following line and double click on it.

Windows Registry Editor Version 5.00

; Add command prompt to right click menu in a folder
[HKEY_CLASSES_ROOT\Directory\Background\shell\Command Prompt]
[HKEY_CLASSES_ROOT\Directory\Background\shell\Command Prompt\command]
@="cmd.exe /s /k pushd %V"

; Add command prompt to right click menu on a folder
[HKEY_CLASSES_ROOT\Directory\shell\Command Prompt]
[HKEY_CLASSES_ROOT\Directory\shell\Command Prompt\command]
@="cmd.exe /s /k cd %L"

[HKEY_CLASSES_ROOT\Directory\shell\PowerShell]
[HKEY_CLASSES_ROOT\Directory\shell\PowerShell\command]
@="C:\\\\Windows\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%L'"

Saturday, March 29, 2014

How do you connect to remote desktop automatically via batch file?

@echo off
set domain=<DOMAIN NAME>
set password=<PASSWORD>
set server=<SERVER NAME or IP>
set user=<USER NAME>
cmdkey /generic:TERMSRV/%server% /user:%domain%\%user% /pass:%password%
start mstsc /v:%server% /f
exit /b

Monday, March 24, 2014

How can you delete files older than 7 days?

my $log_dir = "C:\perlwork\temp";
foreach my $file ( grep {-M > 7} glob("$log_dir/*.log") ) {
        unlink $file;
}

Thursday, March 13, 2014

How do I list the specific types of files in current directory in Perl on windows?

use Cwd;

my $directory = getcwd();

opendir (DIR, $directory) or die "Can't open directory \"$directory\" - $!";
my @filelist = grep(/\.csv$/i, readdir(DIR));;

foreach my $file (@filelist) {
print "$file\n";
}

closedir(DIR);

How can you store contents of config file into a hash-of-array?

my %conf = ();
open (INI, "<config.ini") || die "Can not open - $!" ;
while (my $line = <INI>) {
if (($line=~/^#/) || ($line=~/^;/)) {
#ignore these lines coz they are comments!
}
else {
if($line =~m/^(.*?)=(.*?)$/) {
push @{$conf{NAME}}, $1;
push @{$conf{SIZE}}, $2;
}
}
}
close INI;

# To access each array in hash-of-array
foreach my $key ( keys %conf )  {
    print "$key = @{$conf{$key}}\n";
}

# To access each element in hash-of-array
foreach my $key ( keys %conf )  {
    foreach ( @{$conf{$key}} )  {
        print "$key = $_\n";
    }
}

# To access single element of particular array in hash-of-array
print "${$conf{NAME}}[0]\n";

#config.ini :
# ';' or '#' can be used to comment any pair!
;[ATTRIBUTE=WIDTH]
First Name=15
Last Name=20
Middle Name=10
Member ID=20
SSN=9