Showing posts with label Perl. Show all posts
Showing posts with label Perl. Show all posts

Monday 14 March 2016

How to find size of Hashes in Perl

Hashes as you know are basically key-value pairs. So in Perl, if you want to find the size of hashes, check this out.

Consider a simple practical real-time Perl script for storing stock quotes of various companies.

#!/usr/bin/perl

use strict;
use warnings;

my %stock_quotes;
my @keys;
my $size_of_hash;

%stock_quotes=(
Apple => 102,
Google => 720,
Microsoft => 53,
Yahoo => 34,
Walmart => 67
        );

@keys = keys %stock_quotes;

$size_of_hash = @keys;


print "Stock hash size : $size_of_hash \n";

You see the %stock_quotes is the hash which has key value pairs i.e stock quote values in this case. Now, we store all the keys of the pairs in an array @keys. Note am not storing the values here, just the keys and we then find the size of this array @keys holding all the keys. Thus basically showing the size of the hash with $size_of_hash.

The resultant output is as expected :

Stock hash size : 5

Cheers!

Friday 21 February 2014

Getopts Tutorial - Command line options in Perl

In Perl, if we want the user to pass certain options at command line, we can define the switches in the program code using Getopts. Following is a brief tutorial underlying it's usage with a practical example.

First of all, search the CPAN for Getopt and you'll see a lot of available modules - each with a slightly distinct functionality. All serve the same purpose though - providing a framework for passing user-defined command line options.

Now, install either the Getopt::Long or Getopt::Compact or Getopt::Lucid module from CPAN. I assume you know how to install modules from the terminal. If not, dig in through this blog. You'll get the answers.

In this example, I'll use the highly rated Getopt::Long module. Make sure you refer the module's official documentation link for more details. The following illustration is about it's simple basic usage, just to give you a feel. I'll cover an advanced usage tutorial for this module in another post.

Ok guys, enough talk. Lets code some stuff. Here we go...

use strict;
use warnings;
use Getopt::Long;

my $name;
my $location;

GetOptions (

               'name=s' => \$name,
               'location=s' => \$location,
);

if ($name) {
          print "Welcome $name \n";
}

if ($location) {
          print "Hows the weather at $location \n";

}

Here, "name" and "location" are the options to which we pass an argument. Note that we have mentioned name=s and location=s. The alphabet 's' implies the switch will be of string type. If you want the switch to be of integer type, use i. ( Eg : 'age=i' => \$age ).

Also, the equal sign = indicates that it is a mandatory option. If you want an option to be optional, use the colon : sign ( Something like - 'help:h' => \$help ).

Save the program as Getopts_Ex.pl and now open the terminal. From the command line, run the program as follows :

perl Getopts_Ex.pl -name "IronCladZone" -location "New York"

The output would be as follows :


Note that you have to pass an argument for each mandatory option. If you don't pass an argument, you will get an error. You can also play around by defining a separate function with customized error messages or switches' usage. This can be extremely helpful to a newbie or a layman, informing him how to run the program and how to use the custom switches defined in the script.

The above code contains print statements within the "if" block. You can instead tweak the "if" block to call custom user-defined functions a.k.a subroutines from here and put the print codes in the subroutine. The output will be the same, but the below structure makes it more graceful and secure. In fact, I plan to cover the topic of subroutines in another fresh post. Stay tuned for that as well.

use strict;
use warnings;
use Getopt::Long;

my $name;
my $location;

GetOptions (

               "name=s" => \$name,
               "location=s" => \$location,
);

if ($name) {
          func_name();
}

if ($location) {
          func_location();

}


sub func_name()  {
            print "Welcome $name \n";
}

sub func_location()  {
            print "Hows the weather at $location \n";
}

Folks, do let me know your comments about this post and suggestions on how to improve the quality of the content. Ciao.

Monday 17 February 2014

Perl Message Box Tutorial

Previously, we covered the Perl Listbox example using the Tk module. In this post, we will discuss about using Tk to create a simple Message Box.

First of all, install the Tk Msgbox module from the command line as follows:

sudo cpan Tk::MsgBox

Then consider the following code snippet : 

---------------------------------------------------------

use Tk;
use Tk::MsgBox;

my $m = MainWindow->new;

my $x = $m->MsgBox(
-title=> 'Perl MsgBox Example'
-message=> "Welcome to Tk Message Box"
-type=> 'okcancel'
);

my $button = $x->Show;

---------------------------------------------------------

The output window will be as follows :


In above example, we've used the okcancel box type. The msgbox type can be changed to one of the following : ok, okcancel, yesno, yesnocancel, retrycancel, abortretrycancel.

Even the info icon can be changed to error, warning types if needed.


List all Perl CPAN modules installed on the system

In order to list all the CPAN modules installed on a system, use the following command :

instmodsh

Now you'll see the following menu : 

Available commands are:
   l                      - List all installed modules
   m <module>   - Select a module

   q                     - Quit the program

cmd? l

On entering option l, it will display the complete list of modules installed on the system.

Eg: 

   Net::HTTP
   PDF::API2
   PDF::Report
   PDF::Report::Table
   PDF::Table
   Params::Validate
   Parse::CPAN::Meta
   Perl
   Perl::Destruct::Level
   Perl::OSType
   Probe::Perl
   SOAP::Lite

Monday 3 February 2014

Inserting values in Perl Tk Listbox

Perl programming language can be used to design GUI interfaces as well. Some most known modules used for this are Tk, Prima, Gtk2, wxPerl. Most popular and broadly used module is the Tk module. Thanks to the extensive documentation and easy learning curve.

In this post, we'll cover a basic tutorial using Perl Tk. We will create a basic listbox and insert array values into it.

First of all, download the Tk module and install it. If you're not aware about how to install Perl modules, we'll cover those basics in another post.

Consider the following piece of code :

use Tk;
use Tk::Listbox;

#This is the array containing values, which will be inserted into the listbox

my @values1 = qw(China Russia India Brazil USA UK);

#This is the code for defining the main window size along with the window title.

my $m = MainWindow->new;
$m->geometry("320x300");

$m->title("Listbox values Example");

# This is the definition of the Listbox. Try tweaking its parameters to modify its design.

my $lb = $m->Listbox(
-background =>'Yellow',
-font => 'Helvetica',
-foreground => "Red",
-selectborderwidth => '2',
-selectmode => "single",
-width => "15",
-exportselection => 1
)->pack();

#This is the syntax for inserting values into the defined listbox.

$lb->insert('end', @values1);

MainLoop;

Save the program as ListBox_Eg.pl and run it. (perl ListBox_Eg.pl). The output window would be as follows :


Note the above code will work on Windows and OSX alike, since Perl is a platform independent programming language.

Monday 27 January 2014

Random Key Generator using Perl

When you buy new software, there usually is a license key associated with your copy.  Ever wondered, how these keys get generated? Typically, advanced products use heavily encrypted key codes, while simple old-school vintage softwares used simple keys.

In this post, I'll show you a simple script to randomly create some keys using Perl.

Keys can be generated using different combinations. You could have plain vanilla keys containing only digits or alphanumeric keys or alphanumeric keys mixed with special characters or small letters mixed with capital letters. The choice is yours.

Ok, so in this program, we ask the user to enter the desired length of keys to be generated to make it interactive.

Alternatively, you could skip the user input altogether and hardcode a specific figure for key-length. Eg: $len_str = 16

use strict;
use warnings;

print "Enter the desired length of keys to be generated : \n";

my $len_str = <STDIN>;

my $random_string =&generate_random_string($len_str);

print "$random_string \n";

sub generate_random_string() {

$len_str = shift;

my @chars = ('a'..'z', 'A'..'Z','0'..'9','-','*','%','$'); 

my $random_string;

foreach (1..$len_str) {

$random_string .= $chars[rand @chars];

}

  return $random_string;

}  #end of subroutine

The subroutine generate_random_string contains the main logic of the program. Note that we have used the rand function which is responsible for generating random characters.

Note the line above in script, in which we have mentioned the condition - to include small letters a-z, capital letters A-Z, digits 0-9 and special characters -, *, %, $. Here you could add any other character you want to.

Thursday 23 January 2014

Read command line arguments in Perl

In Perl, the command line arguments are stored in the array @ARGV.

So the first argument passed can be displayed by $ARGV[0]

The second argument passed can be displayed by $ARGV[1] and like wise.

Eg:

If you run a script and pass 3 command line arguments to it :

./eg_script.pl Ironclad Writer 123

The first argument $ARGV[0] = "Ironclad"

The second argument $ARGV[1] = "Writer"

The third argument $ARGV[2] = "123"

Wednesday 22 January 2014

Data types in Perl

Perl interpreter can handle 3 basic data types :


  • Scalar - it stores single values. It must have the $ prefix sign Eg: $myvar
  • Array - it is used to multiple scalar values. It must have the @ prefix sign Eg: @my_array
  • Hash - it uses associate arrays which has key-value pairs. It must have the % prefix sign Eg: %my_hash

Sunday 29 December 2013

Reading files recursively from a directory in Perl

Here's a sample illustrative script to read filenames from within a directory recursively in Perl and then executing some commands is as below:

use strict;
use warnings;

my $dir = "/usr/var/";   <----- here you can mention the location / path of the directory

opendir DIR, $dir;   <---- DIR is the directory handler

my @files = readdir DIR;

foreach my $file(@files) {

// execute_your_own_commands_here

}

closedir DIR;

As you see above, the array @files will store all the filenames within the specified directory.
In the next foreach loop, we perform some set of commands recursively on each of the files.

Splice function in Perl

While using arrays in a Perl program, sometimes you might require only a part or a chunk of the array instead of the whole.

Splice is a function which is used to carve an array and cut a portion out of it.

Consider the following illustration.

Eg:

@arr = ('10', '90', '30', '70', '40', '60');

Now as you may be aware, each value in the array is identified by it's index. The first element of the array is denoted by index 0. The second element is denoted by index 1 and so on...

Let's use the splice function to cut the array:

$portion = splice(@arr, 2, 4);

If you observe above, we have basically specified the range of elements from 2nd to 4th index within the array.

In this case the element on 2nd index from left is 30 (since foremost element's 10's index is 0) and the element on 4th index is 40)

The above command will result into values ('30', '70', '40') getting stored in the @portion array, which is a chunk of the original @arr array.

In general, splice syntax can be remembered as splice (<array-name>, <beginning-index>, <ending-index>)

Chop vs Chomp in Perl

In Perl, the basic difference between the keywords 'chop' and 'chomp' is as follows:

Chop is used to literally chop the last character of a string. It simply deletes the last character.

Eg:

chop garlic;

The output will be garli with 'c' getting chopped off :)

On the other hand, Chomp is used to delete the endline character "\n";

Eg:

$var = "garlic\n";

chomp $var;

The resultant value of $var will be the same string garlic, but with only the newline character getting deleted.

Sunday 22 December 2013

System vs Exec vs Backticks - Perl

In Perl, the main difference between system, exec and backtick is what happens during the compile time.

Just to refresh your memory, the backtick symbol ( ` ) is on the button above tab button.

Here's the comparison:



SystemExecBacktick
System returns a value after a command is run, irrespective of whether the command executed successfully or failed. Exec does not return a value. Backtick is used to capture the output of a command.
Related Posts Plugin for WordPress, Blogger...
eXTReMe Tracker