Saturday, April 2, 2011

Check for Holiday with Perl


In some cases we would like to avoid to execute the script during public holiday e.g. Don’t send alert during holiday. This script contains 2 functions i.e. “load_holiday_file” and “is_holiday” where you can include in your script to check for holiday.

#!/usr/bin/perl
use strict;

my @holidays = ();
my @now = localtime(time());

my $date = sprintf("%02d-%02d-%04d", $now[3], $now[4]+1, $now[5]+1900 );

load_holiday_file(\@holidays, 'holiday.txt');

if (is_holiday(\@holidays, $date)) {
    print "Today is holiday";
}

# Check the date is holiday
# "date_to_check" is in "DD-MM-YYYY" format.
sub is_holiday {
    my $holidays = shift;
    my $date_to_check = shift;
       
    my $counter = 0;
    my $found = 0;
       
    while($counter <= $#{holidays} && !$found) {
        my $holiday = $holidays->[$counter];
               
        if ($date_to_check =~ /^$holiday/) {
            $found = 1;
        }
        else {           
            $counter++;
        }   
    }

    return $found;
}

# Load holiday file
# Holiday file
# 1. DD-MM-YYYY
# 2. DD-MM (Every year on this date)
sub load_holiday_file {
    my $holidays     = shift;
    my $holiday_file = shift;
       
    if (open(HOLIDAY_FILE, $holiday_file)) {
   
        my $line;
        while (defined($line = <HOLIDAY_FILE>)) {   
            chomp($line);
             
            next if ($line =~ /^\s*#/ );
            next if ($line =~ /^$/);
           
            # Trim the string
            $line =~ s/^\s+//;   
            $line =~ s/\s+$//;
                                               
            push @{holidays}, $line;
        }        
        close(HOLIDAY_FILE);
    }
} 



Holiday File

# Holiday file
# 1. DD-MM-YYYY
# 2. DD-MM (Every year on this date)
27-01-2011       
03-02-2011
03-02-2011
22-04-2011
02-05-2011
17-05-2011
09-08-2011
30-08-2011
26-10-2011
06-11-2011
26-12-2011
02-01-2012