Monday, October 8, 2018

Using switch case in Perl

In the following example we can see the usage of switch case in Perl. 

Here we shall be using the 'Switch' CPAN module specifically.

Here the following Program name is 'switch_case.pl'

#!/usr/bin/perl
use Switch;

# Defining an array of numbers
my @arr = (1, 2, 3, 4);

# Selecting any random element from the array
my $randomnumber = $arr[rand @arr];

# using the switch case functionality
switch($randomnumber) {
 case 1 { print "First Element Of Array: $randomnumber\n" } 
 case 2 { print "Second Element Of Array: $randomnumber\n" } 
 case 3 { print "Third Element Of Array: $randomnumber\n" } 
 else   { print "Fourth Element Of Array: $randomnumber\n" } 
}


Steps To Run The Program:
-------------------------
1) On the command prompt goto the directory where the program is created, type the following and hit enter.

perl switch_case.pl

Output of the above program is either of the following lines:

First Element Of Array: 1

or 

First Element Of Array: 2

or 

First Element Of Array: 3

or 

First Element Of Array: 4


Tuesday, March 27, 2018

A Simple Mojolicious Application Using DBI Showcasing Insertion, Updation And Deletion Of Records

In the following example we are building a simple application using Mojolicious which is one of the relatively new, 
light-weight, modern web application frameworks of Perl. 

Here we shall be using the 'Mojolicious::Lite' CPAN module specifically.

Here the following Application or Program name is 'hello_mojo.pl'

#!/usr/bin/perl
use Mojolicious::Lite;

# connect to database
use DBI;
my $dbh = DBI->connect("dbi:SQLite:database.mydb","","") or die "Could not connect";

# creating table if same already not existing
$dbh->do('CREATE TABLE IF NOT EXISTS people (emp_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(255),
 age int)');

# shortcut for use in template and inside routes
helper db => sub {$dbh};

# The following blocks are called routes where respective functionalities are defined to be executed 

# when '/' or base url is called by any method (GET/ POST) 
any '/' => sub {
	my $self = shift;
	my $message;

	# assigning a template variable
	$self->stash(message => '');

	# calling a template by it's first name to render output
	$self->render('index');
};

# when '/insert' url is called by any method (GET/ POST) 
any '/insert' => sub {
	my $self = shift;
	my $name = $self->param('nm');
	my $age  = $self->param('age');

	$self->db->do(qq{INSERT INTO people(name, age) VALUES(?,?)}, undef, $name, $age);
	$self->redirect_to('/');
};

# when '/edit' url is called by any method (GET/ POST) 
any '/edit' => sub {
	my $self = shift;
	my $emp_id = $self->param('emp_id');
	
	# assigning a template variable with respective value
	$self->stash(emp_id => $emp_id);
	$self->render('edit_form');

};

# when '/edit_record' url is called by any method (GET/ POST) 
any '/edit_record' => sub {
	my $self = shift;	
	my $emp_id = $self->param('emp_id');
	my $name = $self->param('nm');
	my $age  = $self->param('age');

	$self->db->do(q[UPDATE people SET name = ?, age = ? WHERE emp_id = ?], undef, $name, $age, $emp_id);
	$self->redirect_to('/');
};

# when '/delete' url is called by any method (GET/ POST) 
any '/delete' => sub {
	my $self = shift;
	my $emp_id = $self->param('emp_id');

	$self->db->do(q[DELETE FROM people WHERE emp_id = ?], undef, $emp_id);
	
	my $message;
	$self->stash(message => 'Record Deleted');	
	$self->render('index');
};

# staring the mojolicious application, should be the last expression in the application
app->start;


# Following segment defines the embedded template definitions, here we have used 2 templates 
one 'index.html.ep' and the other 'edit_form.html.ep'
__DATA__

@@ index.html.ep
% my $sth = db->prepare(qq{select emp_id, name, age from people order by emp_id});


	My Mojolicious Example


	<%= $message %>
	
Enter Name :
Enter Age :


% $sth->execute(); % my $i=0; % while(my ($emp_id, $name, $age) = $sth->fetchrow_array()) { % $i++; % } % $sth->finish();
Sl No:NameAgeAction
<%= $i %> <%= $name %> <%= $age %> Edit / Delete
@@ edit_form.html.ep % my $sth = db->prepare(q{select name, age from people where emp_id = ?}); % $sth->execute($emp_id); % my ($name, $age) = $sth->fetchrow_array(); % $sth->finish(); My Form
Edit Record
Enter Name :
Enter Age :

Steps To Run The Application:
-----------------------------
1) On the command prompt goto the directory where the application is created, type the following and hit enter.

morbo hello_mojo.pl

Output of the above command: Server available at http://127.0.0.1:3000

2) Now the application is running and the desired html output can be viewed in the web browser using 
http://127.0.0.1:3000 or http://localhost:3000 or whatever is the server address using port 3000.


Thursday, February 1, 2018

Sending Email with Amazon Simple Email Service ( SES )

In the following example we are using the Net::AWS::SES::Signature4 module (Signing with signature version 4) to 
send emails using the Amazon SES system. 

Please remember to gather the Amazon AWS access key and secret key from your Amazon AWS account.

#!/usr/bin/perl

use Net::AWS::SES::Signature4;
use MIME::Lite;

our $access_key = 'Provide the Amazon AWS access key';
our $secret_key = 'Provide the Amazon AWS secret key';

##### creating a Net::AWS::SES::Signature4 object
my $ses = Net::AWS::SES::Signature4->new(access_key => $access_key, secret_key => $secret_key);

##### constructing the email structure using the MIME::Lite module
my $msg = MIME::Lite->new(
 From    => 'senderemail@gmail.com',
 To      => 'recipientemail@gmail.com',
 Subject => 'Testing Email Sending Using SES',
 Data    => 'Hello Guyz!',
 Encoding => 'base64',
 Type    => 'text/plain',
 Charset => 'UTF-8'
);

##### adding attributes to the email
$msg->attr('content-type.charset' => 'UTF-8');

##### adding headers to the email
$msg->add( 'Reply-To' => 'senderemail@gmail.com' ) ;

##### posting our constructed email to AWS SES to deliver the same
my $r = $ses->call('SendRawEmail', {
 'RawMessage.Data' => encode_base64( $msg->as_string )
});

##### verifying the email sent status from the response object of AWS SES
unless ( $r->is_success ) {
 printf('Error in SES mail sending: %s' , $r->error_message) ; 
} 
else
{
 printf('SES mail sending successful with message_id %s' , $r->message_id) ; 
}


Output:
-------
On running the Perl script from command line, it will send an email using the Amazon SES.

Auto Posting a tweet along with an image to a Twitter handle via Oauth

In the following example we are using the Net::Twitter module to auto post a tweet along with an image into a twitter account via Oauth. 
Please remember to gather the twitter account consumer key, consumer secret and access token details from twitter developer account.

#!/usr/bin/perl

use Net::Twitter;

my $twitter_username = 'Provide here twitter account username'; # twitter account username
my $twitter_password = 'Provide here twitter account password'; # twitter account password

my $nt = Net::Twitter->new(
  traits          => ['API::RESTv1_1', 'OAuth'],
  consumer_key    => 'Provide here the twitter developer consumer key',
  consumer_secret => 'Provide here the twitter developer consumer secret',
);

my $image_file = '/tmp/flower.png'; # image to be posted in the twitter account
my $message = 'Hello Folks!!!'; # twit to be posted in the twitter account

my $access_token = 'Provide here the twitter app access token';
my $access_token_secret = 'Provide here the twitter app access token secret';


if ($access_token && $access_token_secret) {
  $nt->access_token($access_token);
  $nt->access_token_secret($access_token_secret);
}

my @filename;
@filename = ($image_file) if($image_file);

my $result;

if (scalar(@filename)) {
 $result = $nt->update_with_media({status=>$message,media=>\@filename});
}
else
{
 $result = $nt->update({status=>$message});
}

    unless ( $result->{id} ) {
        #print Dumper($result);
        print qq{Twitter posting unsuccessful\n};
        exit;
    }

    print qq{Twitter posting successful\n};

};

if ($@) {
    print qq{Twitter posting unsuccessful $@\n};
    exit;
}



Output:
-------
On running the Perl script from command line, it will post the specified image and message into the twitter account mentioned in the script.