Apr 29, 2012

use of $_

#!F:\Perl\bin\perl -w
use strict;

1) print "\n", $_ for (1..10);

2)
my %hash = ( a => 100, b => 200, c => 300);
print "\n", $_ for keys(%hash);:

Apr 27, 2012

CPAN - Perl Modules Repository



   



You can find lots and useful perl modules in the site www.cpan.org
The commonly used modules are :
1) strict
2) warnings
3) Time::Local
4) CGI
5) Data::Dumper
6) Carp etc.,


Another way to delete old files in perl

Note: 
1) Please remove comment (#)
2) 'unlink' is the command used to remove file in Unix
 
#!perl
foreach my $file (</path/to/logs/*.log>) {
  next unless -M $file > 7;
  print "Deleting the File $file...\n";
  # unlink $file or die "Failed to remove file $file: $!";
}
-->

Apr 26, 2012

Delete files older than X days on Linux


find /path/to/files* -mtime +5 -exec rm {} \;

This is an example, which deletes files older than 5 days from unix command line itself

Note:
1)  Apply this from unix command line itself

Jun 22, 2008

Array in Perl

Array:

Its a sequenced list of elements.
Array index starts with zero.

use strict;
use warnings;
use Data::Dumper;

my @arr = ("Mother Teresa", "Abraham Lincoln", "Winston Churchill", "Mahathma Gandhi");

print "\n Print Array Values just like that : @arr";

print "\n\n Print Array Values with Dumper : " . Dumper(\@arr);


my @num_arr = qw/100 200 300/;

print "\n First Val : " . $num_arr[0];

print "\n";

Outout :

 Print Array Values just like that : Mother Teresa Abraham Lincoln Winston Churchill Mahathma Gandhi

 Print Array Values with Dumper : $VAR1 = [
          'Mother Teresa',
          'Abraham Lincoln',
          'Winston Churchill',
          'Mahathma Gandhi'
        ];

 First Val : 100
  


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Scalar

Scalar : 

In Perl, scalar can store a single value at any time.
In the following example, $str contains a string value.
We can store any single integer, string, float value in a scalar. It's as simple as that.

E.g., $str1 = 100;
        $str2 = 'test';
        $str3 = 300.2;


use strict;
use warnings;
use Data::Dumper;

#In Perl, scalar can store a single value at any time.
#In the following example, $str contains a string value.
#We can store any single integer, string, float value in a scalar. It's as simple as that.


#Integer
my $num = 300;
print "\n Number : " . $num;

#String
my $str = "Alex Perter John Dane";

#Array
my @arr = split(/ /,$str);

print "\n After Split : " . Dumper(\@arr);
  

Output:
 Number : 300
 After Split : $VAR1 = [
          'Alex',
          'Perter',
          'John',
          'Dane'
        ];


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Get unique elements from string

#!F:\Perl\bin\perl -w
use strict;
use Data::Dumper;
my $abc = "prabhath vamsi vamsi eswar sandhya vinayaka ";

my @arr = split /\s+/, $abc;
my %uniq = map { $_, 1} @arr;
my @final = keys %uniq;
print Dumper(\@final)

map

1)
$str = "2-5,3-9,1-2,8-1,4-7,5-9,20-3,16-9";
@array=split(/,/, $str);
my @a1= (map
{
($left,$right)=split(/-/,$_);
$left*$right;
}
@array
);
print join(",",@a1),"\n";

2)
@array = (20, 3, 1, 9, 100, 88, 75);
my @new_array = (map { $_*2; } @array);
print join(",", @new_array), "\n";

reverse keyword

#!F:\Perl\bin\perl -w
use strict;

my $a=9;
print "Before Reverse:\n", (1..$a);
print "\nAfter Reverse:\n", reverse (1 .. $a);

Get unique keys from different hashes

- As we konw, keys in a hash are unique, but not the values.

#!F:\Perl\bin\perl -w
use Data::Dumper;
use strict;

#Get unique keys from different hashes
my %hash1 = (a=>10,b=>20,c=>30);
my %hash2 = (a1=>10,b1=>20,c1=>30);
my %hash3 = (a=>10,b=>20,c=>30);
my %uniq_hash;
for my $each (keys(%hash1), keys(%hash2), keys(%hash3)) {
$uniq_hash{$each}++;
}
print "\n", $_ for (keys %uniq_hash),"\n";

Get unique elemenets from Arrays

#!F:\Perl\bin\perl -w
use Data::Dumper;
use strict;

#unique elements from different arrays
my @array1 = (10,20,30);
my @array2 = (11,22,33);
my @array3 = (10,20,30);
my %uniq_arr;

for my $each (@array2, @array3, @array1) {
$uniq_arr{$each}++;
}
print "\n", $_ for (keys %uniq_arr),"\n";

' tr ' or ' y '

Removing the duplicate characters from the string:

#!F:\Perl\bin\perl -w
use strict;


#Removing the duplicate characters ('c' , 'd') but not ('e') from the string
my $val = 'abcccdddddeeeeeeeeeeeeecccccc';
print "\n Given String:", $val;

$val =~ y/cd//s; # 'y' is nothing but 'tr'

print "\nAfter :$val\n";

Defining a undefined variable

If a variable is not defined, we can define like this instead of IF block.

#!F:\Perl\bin\perl
use strict;
use warnings;

# Very simple and easy to use
$a;
$a |= "prabhath";
print "\n Value is:", $a;


=cut
We can avoid the unnecessary if and defined code

$a = 'vamsi';
if ( not defined $a) {
$a = 'prabhath';
}
=cut

substitute for n'th occurance

#!F:\Perl\bin\perl -w
use strict;

# Substitue 3rd occurance of 'perl' with 'PERL'
my $text = 'perl is good, perl is better, perl is best';
print "\n INPUT Text:", $text;

my $nth_occurance = 3;
my $count=0;

$text =~ s{(perl)}{
++$count == $nth_occurance ? 'PERL' : $1
}ige;

print "\n OUTPUT Text:", $text,"\n";

Sort an Array

1) For number Array

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array = (20,10,50,40,30); #Unsorted Number Array
print "\n Unsorted Array is: @array";
my @sorted = sort { $a <=> $b } @array;

# '<=>' for numbers only
# 'cmp' used for numbers as well as strings
print "\n sorted Array is: @sorted";
my @sorted = sort { $a cmp $b } @array;

print "\n sorted Array is: @sorted";


2) For String Array

#!F:\Perl\bin\perl -w
use Data::Dumper;
#Unsorted String Array
my @array = qw/sandhya eswar prabhath vamsi/;
print "\n Unsorted Array is: @array";

my @sorted = sort { $a cmp $b } @array;

# 'cmp' can be used for both strings as well as numbers
print "\n sorted Array is: @sorted";

Slurp

- Slurp means reading or writing a file at one shot, instead of
reading or writing line by line.
- Generally slurp if very fast than normal reading a file line by line
- But slurp uses more memory, as it needs to keep th whole file
in a scalar (or) an array, but now a days as everybody is
having enormous amount of hard disk space and RAM, its not
a problem with Slurp.
- But those people where memeory and space concerns are there,
don't go for Slurp
- Some Cpan modules on Slurp are:
1) Slurp # Allows you to read multiple files at a time
2) File::Slurp # Good module for Slurp
3) Perl6::Slurp # Recent module on Slurp with lot more features


The Program will read a folder and read all the files and slurp them into an array and writes to output file
-------------------------------
#!F:\Perl\bin\perl -w

use Slurp;
use File::Slurp;
use Data::Dumper;
use strict;

my $dir='F:\Documents and Settings\Administrator\Desktop\sample_programs';
opendir DIR, $dir or die "cannot open dir $dir: $!";
my @file= readdir DIR;
closedir DIR;

my @final_files;
print "\n All file names before:", Dumper(\@file);

for (@file) {
next if($_ =~/^\.+|\.swp$|\~$/ig);
push (@final_files, $_);
}

my @zx = slurp(@final_files);
write_file('output.txt', @zx);

my @out = File::Slurp::read_file('output.txt');
print "\n output:" , Dumper(\@out);

Get a Random element from an Array

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array = (10,20,30,40,50);
#'rand' gives some random index number
$index = rand @array;
print "\n Random index from an array is:", $index;
$element = $array[$index];
print "\n Random element from an array is:", $element,"\n";

While loop in Perl

We can loop through For/Foreach/While in Perl.

We can discuss while loop now with the following example.



use strict;
use warnings;
use Data::Dumper;

my @names = ("Mother Teresa", "Abraham Lincoln", "Winston Churchill", "Mahathma Gandhi");

print "\n Looping While using counter";

my $i=0;

print "\n Scalar Array Size " . scalar(@names) . "\n";

while ($i <= $#names) {
   print "\n Looping ... " . $names[$i] . "\n";
   $i++;
}

print "\n";
  

Output :
 Looping While using counter
 Scalar Array Size 4

 Looping ... Mother Teresa

 Looping ... Abraham Lincoln

 Looping ... Winston Churchill

 Looping ... Mahathma Gandhi
 


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Example on Greedy Operator ' * '

#!F:\Perl\bin\perl -w
use strict;

my $str = "perl is awesome, I am also awesome";
$str =~ /.*awesome/; # '*' is greedy operator, so it is not satisfied with the first occurance
print $&,"\n"; # perl is awesome, I am also awesome

#To restict the greeedyness to first occurance
#Use '?' operator to restrict the greediness
$str =~ /.*?awesome/;
print $&,"\n"; #perl is awesome

$^O gives the OS name

#!F:\Perl\bin\perl -w
use strict;
print "$^0\n";

Different ways to remove duplicates from array

#!F:\Perl\bin\perl -w
use strict;
use Data::Dumper;

#Remove duplicates from array.
my @array = qw/10 20 20 20 30 40 40 40 50 50 50/;
print "\n Duplicate array: @array";

1) Good

my %hash;
$hash{$_} = 0 for (@array);
# $hash{$_} = () for (@array); #You can do this also

my @final = keys (%hash);
print "\n Unique Array: @final";
print "\n";


2) Best of all

my %hash = map { $_ , 1 } @array;
my @uniq = keys %hash;
print "\n Uniq Array:", Dumper(\@uniq);


3) Costly process as it involves 'greping'

my %saw;
my @out = grep(!$saw{$_}++, @array);
print "\n Uniq Array: @out \n";

How to create an unique array

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array_with_duplicate_elements = qw/ 1 2 3 4 5 5 5 5 4 4 4/;
my %hash = map { $_, 1 } @array_with_duplicate_elements;
my @unique_array = keys %hash;
print Dumper(\@unique_array);

Hash in Perl

Hashes are like named key value pairs.
Keys are always unique, Values can be anything.
It's best practice to use hashes, they are efficient.

 

use strict;
use warnings;
use Data::Dumper;

my %hash = (a => 10,
            e => 40,
            c => 30,
            d => 40,
            b => 20,
            a => 100);

#Print Keys
print "\n Only Keys:\n" . Dumper(keys %hash);

print "\n\n";
#Print Values
print "\n Only Values:\n" . Dumper(values %hash);


print "\n\n";
#Print Keys and Values
while ( my ($key, $value) = each %hash)
{
   print "$key => $value\n";
}

print "\n\n";



#Print Keys
print "\n Sorted Keys:\n" . Dumper(sort keys %hash);

print "\n\n";
#Print Values
print "\n Sorted Values:\n" . Dumper(sort values %hash);
  
Output:

 Only Keys:
$VAR1 = 'e';
$VAR2 = 'c';
$VAR3 = 'a';
$VAR4 = 'b';
$VAR5 = 'd';



 Only Values:
$VAR1 = 40;
$VAR2 = 30;
$VAR3 = 100;
$VAR4 = 20;
$VAR5 = 40;


e => 40
c => 30
a => 100
b => 20
d => 40



 Sorted Keys:
$VAR1 = 'a';
$VAR2 = 'b';
$VAR3 = 'c';
$VAR4 = 'd';
$VAR5 = 'e';



 Sorted Values:
$VAR1 = 100;
$VAR2 = 20;
$VAR3 = 30;
$VAR4 = 40;
$VAR5 = 40;
  


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Formatted Print

#!F:\Perl\bin\perl -w
use strict;

printf("\n%.2f", 19.9500000000000000000);
printf("\n%.3f", 19.9500000000000000000);

How to get all files in a directory

#!F:\Perl\bin\perl -w
use strict;

opendir(DIR, ".");
my @files = readdir(DIR);
closedir(DIR);
foreach my $file (@files) {
print "$file\n";
}

Count no.of digits in a string

#!F:\Perl\bin\perl -w
use strict;

my($test,$number);
$test = "12344tyyyyy456";
$number = ($test =~ tr/[0-9]/[0-9]/);
print "Number of digits in variable is : $number ";

How to reverse hash or Lookup a hash by value instead of key

But remember keys are uniue but values are not, so before reversinf the
original array values should be unique, after reverse these values become
keys of reversed array. Otherwise things will not work out in ur way.
Anyways just give a try
# Eg: %hash = ( a => 10, b => 10, c => 10, d => 10);

Example1:
#########
#!F:\Perl\bin\perl -w
use Data::Dumper;

# The following is good and easy to use but not tat much efficient in terms of space,
as it needs to keep a copy of the hash.

%hash = ( a => 10, b => 20, c => 30, d => 40);
print "\n Hash before reverse:", Dumper(\%hash);

%reverse = reverse %hash; # It will reverse the hash

print "\n Hash after reverse :", Dumper(\%reverse);
print "\n";


Example2:
#########
#!F:\Perl\bin\perl -w
use Data::Dumper;

# The following is sapce efficient

%hash = ( a => 10, b => 20, c => 30, d => 40);
print "\n Hash before reverse:", Dumper(\%hash);
while (($key, $value) = each %hash) {
$hash{$value} = $key;
}
print "\n Hash after reverse :", Dumper(\%hash);
print "\n";

How to use upper case (or) lower case

#!F:\Perl\bin\perl -w
use strict;

my $text = 'india is a great country';
print "\n Before:", $text; # india is a great country
$text = uc $text; # To make $text to upper case
print "\n After :", $text,"\n";

my $text = 'india is a great country';
print "\n Before:", $text; # india is a great country
$text = lc $text; # To make $text to lower case
print "\n After :", $text,"\n";

Make first letter of every word in a string to Upper case

#!F:\Perl\bin\perl -w
use strict;

my $text = 'india is a great country';
print "\n Before:", $text; # india is a great country
$text =~ s/(\w+)/\u$1/g; # \u option is used
print "\n After :", $text,"\n"; # India Is A Great Country

use of $_

#!F:\Perl\bin\perl -w
use strict;

1) print "\n", $_ for (1..10);

2)
my %hash = ( a => 100, b => 200, c => 300);
print "\n", $_ for keys(%hash);: