Wednesday, November 5, 2014

Working with Amazon SQS in Perl

The following perl program shows how to access the Amazon SQS (Simple Queue Service) for storing and retrieving messages using the Amazon::SQS::Simple module.
#!/usr/bin/perl

use Amazon::SQS::Simple; # module required for accesing Amazon SQS

# Amazon AWS credentials
my $access_key = 'xxxxxxxxxxxxxxxx'; # Your AWS Access Key ID
my $secret_key = 'xxxxxxxxxxxxxxxx'; # Your AWS Secret Key

my $sqs = new Amazon::SQS::Simple($access_key, $secret_key); # Create a SQS object providing the AWS (Amazon Web Services) credentials

my $queue = $sqs->CreateQueue("queue name"); # optional, create a queue if required or else follow the next step for accesing an old queue

# or

my $queue = $sqs->GetQueue("queue url"); # create an object for accessing an old queue  

$queue->SendMessage("Hello World!!!"); # store "Hello World!!!" message in the AWS queue

my $msg = $queue->ReceiveMessage(); # retrieving a stored message from the AWS queue

my $message = $msg->MessageBody(); # fetch the message body

print $message; # displaying the message body on the screen

$queue->DeleteMessage( $msg->ReceiptHandle() ); # delete the retrieved message from the queue, if required 

$queue->Delete(); # delete the AWS queue, if required 


Output:
-------
On running the Perl script from command line, it will output "Hello World!!!" on the screen reading from the AWS queue.