Wednesday, September 26, 2012

Reading complete property file and return hash

# Function Name    : readInputFile
# Input                    : 1. Input file name
#                              2. Delimiter.  if not specified then = will be used
# Output                : None
# Description            : This subroutine will parse input file having key-value pair and create hash.  # as first character in file will be ignored
sub readInputFile($$)
{
    my ($file, $delim) = @_;
    $file = &convertSlash(&trim($file));
    $delim = &trim($delim);

    my %list;

    if ($delim eq "")
    {
        $delim = "=";
    }

    open (FI, $file);
    while()
    {
        my $line = $_;
        chomp $line;
        $line = &trim($line);

        unless ((substr($line, 0, 1) eq "#")  || ($line eq ""))
        {
            my ($key, $value) = split($delim, $line);
            $key = &trim($key);
            $value = &trim($value);

            if (exists $list{$key})
            {
                $value =  $list{$key}."::$value";
            }

            $list{$key} = $value;
        }
    }
    close (FI);
    return %list;
}

Getting value of a parameter from a property file

# Function Name    : parseDataFile
# Input            : filename with path and parameter whose value is required
# Output        : value of the the parameter from file
# Description    : This funtion will parse given file and return the value of the parameter
sub parseDataFile($$)
{
    my ($file, $parameter) = @_;
    $file = &convertSlash($file);
    open (FI, $file) or die "\nError :: :: Could not open file-${file}!!!\n";;

    while ()
    {
        my ($str) = $_;
        chomp ($str);
        $str = &trim($str);

        if ((substr($str, 0, 1) eq "#") || ($str eq ""))
        { # do nothing.  This means this line is commented or empty.
        }
        else
        {
            my $key = substr($str, 0, index($str, "="));
            my $value = substr($str, index($str, "=") + 1);
           
            if ($key eq $parameter)
            {
                return &trim($value);
            }
        }
    }
    close (FI);
    return "";
}

Put data in a file

# Function Name    : store_data
# Input            : filename with path and string data to be stored
# Output        : none
# Description    : This funtion will create the given file and store given data in it.
sub store_data($$)
{
    my ($file, $str) = @_;
    $file = convertSlash($file);
    if (-e $file)
    {
        open (FO, ">>$file");
    }
    else
    {
        open (FO, ">$file");
    }
    print FO $str;
    close (FO);
}

Read content from a file

# Function Name    : get_data
# Input            : filename with path
# Output        : none
# Description    : This funtion will retrieve data from the given file and return it as a single string
sub get_data($)
{
    my ($file) = @_;
    $file = convertSlash($file); #
    open (FI, $file);
    my (@data) = ;
    my ($str) = join ("\n", @data);
    chomp $str;
    close (FI);
    return $str;
}

Getting your IP Address with Perl

# Way-1
use Sys::Hostname;
use Socket;

my($addr)=inet_ntoa((gethostbyname(hostname))[4]);
print "$addr\n";

# Way-2
my @ip = ();
my($host, $aliases, $addr_type, $length, @address) = gethostbyname('localhost');
# @address should contain the loopback - 127.0.0.1
# you can skip it if you want
foreach my $address (@address)
{
    push(@ip, join('.', unpack('C4', $address)));
}
($host, $aliases, $addr_type, $length, @address) = gethostbyname($host);
# @addresscontains our public IP address(es)
foreach my $addr (@address)
{
    push(@ip, join('.', unpack('C4', $address)));
}





# Print IP addresses now
foreach my $ip (@ip)
{
    print $ip, "\n";
}

Tuesday, September 25, 2012

Hashes in Perl

This blog talks about below topics related to Hashes:

  1. Defining an hash
  2. Printing an hash
  3. Getting Length of an hash
  4. Adding elements in an hash
  5. Removing elements in an hash
  6. Clearing complete hash
  7. Sorting an hash by key
  8. Sorting an hash by value
  9. Checking if key in hash exists

NOTE: Hashes are complex list data, like arrays except they link a key to a value. To define a hash, we use the percent (%) symbol before the name.

Define an hash

# Define an hash
%denomination = ("Hundred", 100, "Ten", 10, "Thousand", 1000);
 
# Alternate way
%denomination = ( "Hundred", 100,
           "Ten", 10,
           "Thousand", 1000 );  

# One more way
%denomination = (
        Hundred => '100',
        Ten => '10',
        Thousand => '1000',
    );
 

Print an hash

# Print an hash
print %denomination

# Output: Thousand1000Hundred100Ten10
 
# Another way
while (($key, $value) = each(%denomination))
{
     print "$key, $value\n";
} 
# Output: 
Thousand, 1000
Hundred, 100
Ten, 10 
 
# One more way
foreach $key (keys %denomination) 
{
     print "$key: $denomination{$key}\n";
} 
# Output: Thousand, 1000
Hundred, 100
Ten, 10 
 

Getting Length of an hash

# Getting Length of an hash
%denomination = ("Hundred", 100, "Ten", 10, "Thousand", 1000);
print scalar (keys %denomination), "\n";
# Output: 3
 

Adding elements in an hash

%denomination = ("Hundred", 100, "Ten", 10, "Thousand", 1000);
while (($key, $value) = each(%denomination))
{
     print "$key, $value\n";
} 
print "\n";

$denomination{One} = "1";
$denomination{'Lakh'} = "100000";
while (($key, $value) = each(%denomination))
{
     print "$key, $value\n";
} 
# Output:
Thousand, 1000
Hundred, 100
Ten, 10

Thousand, 1000
Hundred, 100
Lakh, 100000
Ten, 10
One, 1
 

Removing elements in an hash

%denomination = ("Hundred", 100, "Ten", 10, "Lakh", 100000, "Thousand", 1000, "One", 1);
while (($key, $value) = each(%denomination))
{
     print "$key, $value\n";
} 
print "\n";

# Deletes the element pairs
delete($denomination{One});
delete($denomination{Lakh});

while (($key, $value) = each(%denomination))
{
     print "$key, $value\n";
} 
# Output: 
Thousand, 1000
Hundred, 100
Lakh, 100000
Ten, 10
One, 1

Thousand, 1000
Hundred, 100
Ten, 10
 

Clearing complete hash

%denomination = ("Hundred", 100, "Ten", 10, "Lakh", 100000, "Thousand", 1000, "One", 1);
while (($key, $value) = each(%denomination))
{
     print "$key, $value\n";
} 
print "\n";

# Deletes complete Hash
undef %denomination;

while (($key, $value) = each(%denomination))
{
     print "$key, $value\n";
} 
# Output: 
Thousand, 1000
Hundred, 100
Lakh, 100000
Ten, 10
One, 1
 

Sorting an hash by key

# Sorting an hash by key
%denomination = ("Hundred", 100, "Ten", 10, "Thousand", 1000);
foreach $key (sort keys %denomination) 
{
     print "$key: $denomination{$key}\n";
}
# Output: 
Hundred: 100
Ten: 10
Thousand: 1000
 

Sorting an hash by value

# Sorting an hash by value
%denomination = ("Hundred", 100, "Ten", 10, "Thousand", 1000);
foreach $value (sort {$denomination{$a} cmp $denomination{$b} } keys %denomination)
{
     print "$value $denomination{$value}\n";
}
# Output: 
Ten: 10
Hundred: 100
Thousand: 1000
 

Checking if key in hash exists

print "Exists\n" if exists $array{$key};
print "Defined\n" if defined $array{$key};
print "True\n" if $array{$key};

# Output: Ten: 10 Hundred: 100 Thousand: 1000 

Getting Size of a directory

# Function Name    : getDirSize
# Input                    : File or Folder name
# Output                : Size in bytes
# Description            : This subroutine will return the size in bytes for given folder or file
#
sub getDirSize($)
{
    my $dir = shift;
    my $size = 0;            
    find(sub { $size += -s if -f $_ }, "$dir");
    return $size;
}

# Function Name    : format_size
# Input                    : 1. Size in bytes and 2. digits after decimal. Default is zero
# Output                : Size in KB or MB or GB
# Description            : This subroutine will return the size in highest possible unit
#
sub format_size($$)
{
    my $size = shift;
    my $decimal = shift;

    if ((not defined $decimal) || (&trim($decimal) == ""))
    {
        $decimal = 0;
    }

    return "${size}bytes" if ($size < 1024) ;
    $size = sprintf("%.${decimal}f", $size/1024);
    return "${size}KB" if ($size < 1024)  ;
    $size = sprintf("%.${decimal}f", $size/1024);
    return "${size}MB" if ($size < 1024)  ;
    $size = sprintf("%.${decimal}f", $size/1024);
    return "${size}GB";
}