Wednesday, September 26, 2012

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

Tuesday, September 18, 2012

Arrays in Perl

 This blog talks about below topics related to Arrays:

  1. Defining an array
  2. Printing an array
  3. Defining big array
  4. Getting Length of an array
  5. Adding and Removing elements in an array
  6. Slicing array elements
  7. Replacing Array element (splice)
  8. String to array
  9. Array to String
  10. Sorting an array
  11. Searching a element in an array
  12. Comparing 2 arrays

NOTE: Each element of the array can be indexed using a scalar version of the same array. When an array is defined, PERL automatically numbers each element in the array beginning with zero. This phenomenon is termed array indexing.

Define an array

# Define an array
@names = ("Rinkesh","Bansal","Rinku");
 
# Define an array alternate way
@names = qw(Rinkesh Bansal Rinku);


Print an array

# Print array
# 1. Displays all members separated by space
print "@names";
# Output: Rinkesh Bansal Rinku

# 2. Displays all members without any separator
print @names;
# Output: RinkeshBansalRinku


# 3. Display each array element properly
foreach my $name (@names)
{
    print "$name\n";
}
# Output:
Rinkesh
Bansal
Rinku


# 4. Display each array element properly. This is array indexing
print "$name[0]\n";
print "$name[1]\n";
print "$name[2]\n";
# Output:
Rinkesh
Bansal
Rinku

# 5. Display each array element properly. This is array indexing using negative integers

print "$name[0]\n";
print "$name[-1]\n";
print "$name[-2]\n";

# Output:
Rinkesh

Rinku
Bansal
 


Define big array

# Define array with multiple values to save time

@10 = (1 .. 10);
@100 = (1 .. 100);
@1000 = (100 .. 1000);
@abc = (a .. z);


print "@10\n";


print "@100\n";

print "@1000\n";

print "@abc\n";

# Output: it will print 1 to 10 in first line, 1 to 100 in next, 100 to 1000 in next and a to z in last line




Getting length of an array

#  Finding the length of an Array
print scalar(@10),"\n";

print scalar(@100),"\n";
print scalar(@1000),"\n";
print scalar(@abc),"\n";
# Output:
10
100
901
26



Adding and Removing Elements

# Below functions were available to add/remove elements
  • push(@array, Element): adds an element to the end of an array
  • unshift(@array, Element): adds an element to the beginning of an array
  • pop(@array): removes the last element of an array
  • shift(@array): removes the first element of an array
  • delete $array[index]: Removes an element by index number

 add_remove.pl

# Define an array
@count = ("one","two","three");

# Add Elements
push(@count, "four");
print "@count\n";
unshift(@count, "five");
print "@count\n";

# Remove Elements
pop(@count);
print "@count\n";
shift(@count);

# BACK TO HOW IT WAS
print "@count\n";

# Output:
one two three four
five one two three four
five one two three
one two three

Slicing Array Elements

slice1.pl


@count = ("one","two","three");
@sliceCount = @count[0,2];
print "@sliceCount\n";

# Output: one three

slice2.pl

@100 = (1..100);
@slice100 = @100[10..20,50..60,90..100];
print "@slice100";

# Output:
11 12 13 14 15 16 17 18 19 20 21 51 52 53 54 55 56 57 58 59 60 61 91 92 93 94 95 96 97 98 99 100



Replacing Array Elements (Splice)

Usage: splice(@array,first-element,sequential_length,name of new elements)

splice1.pl
@nums = (1..20);
splice(@nums, 5,5,21..25);
print "@nums\n";

# Output: 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20
# Explanation: Actual replacement begins after the 5th element, starting with the number 6 in the example above. Five elements are then replaced from 6-10 with the numbers 21-25.


String to Array (split)

Usage: split(delimiter, String)
delimiter is the character using which string will be splitted

split1.pl
$string = "Welcome-to-Hell";
$name = "Rinkesh,Rinku,Bansal";

@array = split('-',$string);
@names = split(',',$name);

print "@array\n";
print "@names\n";

# Output: 
Welcome to Hell
Rinkesh Rinku Bansal


Array to String (join)

Usage: join(delimiter, Array)
delimiter is the character using which join will happen

join1.pl
@names = ("Rinkesh","Rinku","Bansal");
@array = qw(Welcome to Hell);

$name = join(",",@names);
$string = join(" ",@array);

print "$name\n";
print "$string\n";

# Output: 
Rinkesh,Rinku,Bansal 
Welcome to Hell


Sorting Arrays (sort)

Usage: sort(Array)
The sort() function sorts each element of an array according to ASCII Numeric standards. Please view ASCII-Table for a complete listing of every ASCII Numeric character.


sort1.pl
@first = qw(one two three four five);
@second = qw(one Two three Four five);

@first = sort(@first);
@second = sort(@second);

print "@first\n";
print "@second";

# Output: 
five four one three two
Four Two five one three
# Explanation: Capital letters have a lower ASCII Numeric value than lower letters.  Best option is to convert all array elements to lower characters and then sort to get accurate result

sort2.pl

@first = qw(one two three four five);
@second = qw(one Two three Four five);

@first = sort(@first);
foreach $temp (@second)
{
    push(@second_lc, lc($temp));
}
@second_lc = sort(@second_lc);

print "@first\n";
print "@second_lc";

# Output: 
five four one three two
five four one three two

Searching a element in an array

my $str = "three";
my @count = ("one","two","three");

if ($str ~~ @count)
{
    print "\n$str exists\n";
}
else
{
    print "\n$str doesn't exists\n";
}

# Output:
three exists


Comparing 2 arrays


my @first = qw(one three two four five);
my @second = qw(one two three four five);

if (@first ~~ @second)
{
    print "array matches\n";
}
else
{
    print "\nArray doesn't match\n";
}

@first = sort(@first);
@second = sort(@second);

if (@first ~~ @second)
{
    print "array matches\n";
}
else
{
    print "\nArray doesn't match\n";
}

#Output:
Array doesn't match
array matches