5% assure discount from here only

Sunday, January 30, 2011

(18) Difference between Array and Hash?

Solution :

Both datatypes are used in PERL. Both of them are very useful in their respect.

Hash vs Array :-

(i) The basic differnce is the order maintain by both, array always keeps the order of elements inserted but hash will not do the same.

(ii) If data is at large level, than hash is best option as compare to array and at small level, traversing in array is much quicker than hash.

(iii) The symbol difference is there, array always nominated by @ whereas hash is denoting by % symbol.

(iv) The brackets differnce is there, array uses [] parenthesis whereas hash uses {} curly braces.

(v) The elements can be access from array by using index ($array[1]) whereas in hash use keys ($hash{'keys'}) for the same.

(vi) Declaration of both :

my @array = (1,2,3,4,5,6);

foreach my $i(@array){
print $array[$i];
}

my %hash = (1,2,3,4,5,6);

foreach my $keys(keys %hash){
print $keys." => ".$hash{$keys}."\n";
}

Thursday, January 27, 2011

(17) How to send MAIL from perl script?

Solution :

There are so many ways to send MAIL from perl script. Out of them the simplest perl script is here :

To run this the only thing is required the CPAN module Mail::Sendmail.

Perl, being perl, provides the programmer with more than one ways to do same thing, sending email included.
Simple platform independent e-mail from your perl script. Only requires Perl 5 and a network connection.
Mail::Sendmail contains mainly &sendmail, which takes a hash with the message to send and sends it. It is intended to be very easy to setup and use.

After installing the module, you have to run this command on terminal:

service sendmail restart

use Mail::Sendmail;

%mail = ( To => 'you@there.com',
From => 'me@here.com',
cc => 'if any', # optional
bcc => 'if any' # optional
Message => "This is a very short message"
);

sendmail(%mail) or die $Mail::Sendmail::error;

print "OK. Log says:\n", $Mail::Sendmail::log;

(16) How to send SMS from perl script?

Solution :

To send sms you need a gateway that is willing to accept your message and dispatch to the respective networks. For this you need to register and stuff which is a tedious process.

It is very simple to send a SMS from perl script, there are so many ways to do that. Out of them i am going to post some of the ways for the same.

(1) Send SMS via 160By2

To use this script only 2 thing are required :

(i) CPAN module Net::SMS::160By2
(ii) An A/C with http://www.160by2.com/

use Net::SMS::160By2;

my $obj = Net::SMS::160By2->new($username, $password);

$obj->send_sms($msg, $to);

This is how you can send SMS to any mobile number in
India, Kuwait, UAE, Saudi, Singapore, Philippines & Malaysia at present.

(2) Send SMS via Way2SMS

To use this script only 2 thing are required :

(i) CPAN module Net::SMS::WAY2SMS;
(ii) An A/C with http://www.way2sms.com/

use Net::SMS::WAY2SMS;

my $s = Net::SMS::WAY2SMS->new(
'user' => 'xyz' ,
'password' => 'xyzpassword',
'mob'=>['98********', '9**********']
);

$s->send('Hello World');

Wednesday, January 26, 2011

(15) How to write a simple chat program in Perl script?

Solution :

Chat is a useful application that allows a number of people on the World Wide Web to talk to one another simultaneously. Now You can easily make chat using PERL script, there are so many options are available for this.

To make this possible, you must have following cpan module install on your system.

IO::Socket;
IO::Socket::INET;

Then create 2 .pl file, named recieve.pl and sender.pl, to recieve message and send message accordingly.

Put the following code in recieve.pl

my $reciever = new IO::Socket::INET (
        LocalHost => 'localhost',  # can be ip addr of machine if u r 
                                                      using another machine
        LocalPort => '9000',  # port should be same
        Proto => 'tcp',
        Listen => 1,
        Reuse => 1,
     ); die "Could not create socket: $!\n" unless $reciever;

my $new_sock = $reciever->accept();
while(<$new_sock>) {
    print $_;
}
close($reciever);

Put the following code in sender.pl

my $sender = new IO::Socket::INET (
        PeerAddr => 'localhost', # ip addr of machine if u r 
                                                      using another machine
        PeerPort => '9000', # port should be same
        Proto => 'tcp', );
    die "Could not create socket: $!\n" unless $sender;

print $sender "Hi Reciever ";
close($sender);


First run the reciever.pl on terminal 1 and than sender.pl on terminal 2.

Tuesday, January 25, 2011

(14) How to write a simple Perl Database Script?

Solution :

Perl packages enabling your Perl scripts to create and modify databases in standard Unix formats. Perl programmers, like programmers of any other language, typically need to store large amounts of data. Even
though Perl is an exceptional language for text processing, in many circumstances, a more structured
database-like format offers quicker access. In addition, it may also be necessary for a Perl script
to read or write a database that is also accessed through a C program.

Here is the very simple script of perl database connection. The database can be Oracle, Mysql etc etc.

use DBI;

$dbh = DBI->connect("dbi:mysql:xyz", $username, $password)
or die $DBI::errstr;

(13) How to fetch gmail content?

Solution :

Now you can access gmail contents via PERL scripting and can put content accordingly.

use WWW::Mechanize;
$mech = WWW::Mechanize->new;
$mech->get( "https://www.gmail.com/" );
$mech->content();
$mech->submit_form(
form_number => '1',
fields => {
Email => $username,
Passwd => $password,
}
);

my $inbox_url = "https://mail.google.com/mail/?ui=html&zy=e";
$mech->get($inbox_url);
$mailbox = $mech->content();

(12) How to make a hash remember, the order put elements into it?

Solution :

Ordinarily Perl does not guarantee the order of items in a hash to be in any predictable order.
If this is important you can easily add a "keep-in-order" behavior to a particular hash by "tying"
that hash to the Tie::IxHash module. Of course you must first use the module, then, once you tie
your hash to this module, the module will automatically add the desired behavio

Solution :

Use the Tie::IxHash from CPAN.

use Tie::IxHash;

tie my %myhash, 'Tie::IxHash';

(11) How to sort a hash by value/key?

Solution :

Sorting the output of a Perl hash by the hash key is fairly straightforward. It involves two Perl
functions, keys and sort, along with the good old foreach statement.

(i) sort a hash by key

my %hash = (
"a" => 1,
"c" => 3,
"d" => 4
);

my @keys = sort { $a cmp $b } keys %hash;

foreach my $key ( @keys ){
print $key, $hash{$key};
}

(ii) sort a hash by value

my %hash = (
"a" => 1,
"c" => 5,
"d" => 4
);

my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;

foreach my $key ( @keys ){
print $key, $hash{$key};
}

(10) How to know how many entries are in a hash?

Solution :

my $key_count = keys %hash; # must be scalar context!

If you want to find out how many entries have a defined value than:

my $defined_value_count = grep { defined } values %hash;

(9) How to count the number of occurrences of a substring within a string?

Solution :

$string = "-9 55 48 -2 23 -76 4 14 -44";
while ($string =~ /-\d+/g) {
$count++;
}
print "There are $count negative numbers in the string";

(8) How to access or change a particular characters of a string?

Solution :

$string = "Just another Perl Hacker";
$first_char = substr( $string, 0, 1 ); # 'J'

To change part of a string, you can use the optional fourth argument
which is the replacement string.

substr( $string, 13, 4, "Perl 5.8.0" );

(7) How do I strip blank space from the beginning/end of a string?

Solution :

A substitution can do this for you. For a single line, you want to
replace all the leading or trailing whitespace with nothing. You
can do that with a pair of substitutions:

(i) To remove leading space
s/^\s+//;

(ii) To remove Trailing space
s/\s+$//;

(6) How do I reverse a string?

Solution :

my $string = "problems";
my $reversed = reverse $string;
print $reversed; # output is smelborp;

(5) Does Perl have a round() function?

Solution :

The POSIX module (part of the standard Perl distribution)
implements ceil(), floor().

use POSIX;

$ceil = ceil(3.5); # 4
$floor = floor(3.5); # 3

Monday, January 24, 2011

(4) How do I find the index of the last element in an array?

Solution :

my @a=(1,2,3,4,5,6);
my $lastindex=$#a;
print $lastindex;

(3) How to reverse array elements?

Solution :

my @a = ( 1 ,4,2, 9,10 );
my $length = scalar(@a);
my @b;
for(my $i=0;$i<=$length;$i++){ my $j = $a[$length - $i]; push(@b, $j); } print @b;

(2) How do i get the last element of array?

Solution:

my @array = (1,2,3,45,12,232,23);

print $array[$#array];

(1) How to remove duplicate element from an array?

Solution :

There are so many solution of that particular problem, but out of
them i had provided the 2 shortest solution overhere.
(1)
use List::MoreUtils qw(uniq);
my @A = (1,2, 2,4, 3, 4, 5) ;
my @B = uniq @A;
print @B;

(2)

my @A = (1,2, 2,4, 3, 4, 5) ;
my %hash = "";

foreach(@A){
$hash{$_} = $_;
}

my @b = keys %hash;
print @b;