Tuesday, May 14, 2013

Perl : Remove duplicate elements from arrays

How to remove duplicate element from arrays in Perl? Let us see in this article how can duplicates be removed in different ways?

1. Copying distinct elements to new array using grep function:
my @arr=qw(bob alice alice chris bob);
my @arr1;
foreach my $x (@arr){
        push @arr1, $x if !grep{$_ eq $x}@arr1;
}
print "@arr1";
   A loop is run on the array elements. For every element, it is checked to find out whether the element is already present in the new array. If present, it is skipped, else added to the new array.

Wednesday, April 10, 2013

Perl - 6 examples to fetch date / time without Linux date command

How to fetch date and time related stuff within in Perl?
   Sometimes, Perl developers resort to using of Unix system date command to fetch a date or time within Perl script. This is not needed at all since Perl itself has a set of built-ins using which dates and epoch can be retrieved easily without using the system date command. In this article, let us see how to simulate the date related commands in Perl.

1. Getting the date command output:
Linux command:
$ date
To get the date command like output in Perl:

Tuesday, March 26, 2013

Perl - How to find the sum of digits in a number?

How to find the sum of all the digits in a number or a string? OR How to find the sum of all elements in array? Let us see the different ways how it can be done in Perl?

1. Divide and accumulate:
my $x=3456;
my $sum=0;
while ($x) {
        $sum+=$x%10;
        $x/=10;
}
print $sum;
  The digits are extracted by taking the modulus of the number with 10, and then dividing the number by 10. This is repeated till the original number becomes zero at the end of which the sum is retrieved.

Thursday, March 14, 2013

How to remove leading zeros in a string in Linux?

How to remove leading zeros in a variable or a string?

Let us consider a variable "x" which has the below value :
$ x=0010
$ echo $x
0010
1. Using typeset command of ksh:
$ typeset -LZ x
$ x=0010
$ echo $x
10
   The variable x is declared using the typeset command. The -Z option of typeset will strip the leading zeros present when used along with -L option.

Tuesday, February 26, 2013

Perl - What is __DATA__ ?

What is __DATA__ ? Why is it used?
    Generally, Perl reads data from a file which in the Perl program can be accessed using open and readline functions. However, for users who just want to test something for an urgent requirement, it is pretty boring to put the test data in a file and access it using the open and readline functions. The solution for this : __DATA__.

   Let us consider a sample text file:
$ cat f1.txt
AIX,1
Solaris,2
Unix,3
Linux,4