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 => [':', ' ', '-'],
                                 );