[WpProQuiz 1]
[WpProQuiz_toplist 1]
Learning through sharing
[WpProQuiz 1]
[WpProQuiz_toplist 1]
This is one of the questions asked in many Perl related job interviews. See the question here: http://www.aliencoders.org/content/interview-questions-perl-freshers-and-experienced
There will be some situations when you will need to know about installed modules, its version or you may need to check if required module is installed or not with mentioned version or higher than that.
1. To list all installed Perl modules using perl script
[perl]
#!/usr/bin/perl #change the path with your perl location
use strict;
use warnings;
use ExtUtils::Installed; # By default this module will be available in Perl
my $instmod = ExtUtils::Installed->new();
foreach my $module ($instmod->modules()) {
my $version = $instmod->version($module) || “Version Not Found.”;
print “$module version=$version \n”;
}
[/perl]
2. To list installed Perl modules using command line in Linux box
Try instmodsh command in linux box
and then type l to list modules or m to give particular module name or q to quit
[code] $ instmodsh[/code]
Output:
[code]Available commands are:
l – List all installed modules
m – Select a module
q – Quit the program
cmd?[/code]
At cmd? prompt type l to list all installed modules:
[code]cmd? l[/code]
Output:
[code]Installed modules are:
Archive::Tar
CPAN
Compress::Zlib
MIME::Lite
Module::Build
Net::Telnet
PAR::Dist
Perl
Spiffy
Test::Base
Test::Simple
XML::Simple
cmd?
[/code]
This command itself is a perl script that use ExtUtils::Installed module. Try following command to see its source code:
[code]$ vi $(which instmodsh)[/code]
For more details, visit this link: http://perldoc.perl.org/instmodsh.html
3. To compare and check installed Perl modules with respect to given modules with its version
[perl]
#!/usr/bin/perl
use strict;
use warnings;
my @modules = ([‘SOAP::Lite’, 0.50],
[‘IO::Socket’, 0],
[‘HTML::Parser’, 3.26],
[‘LWP’, 5.65],
);
print “\n”,
“==========================\n”,
“Testing for the given Perl modules\n”,
“===========================\n”;
for my $arr_ref (@modules) {
my($mod, $ver) = @$arr_ref;
print “$mod” . ($ver ? ” (version >= $ver)” : “”) . “\n”;
eval(“use $mod” . ($ver ? ” $ver;” : “;”));
if ($@) {
my $msg = $ver ?
“\tEither it doesn’t have $mod installed,\n” .
“\tor the version that is installed is too old.\n” :
“\tIt does NOT have $mod installed.\n”;
print “$msg\n”;
}
else {
print “\tYour system has $mod installed ” .
“with version @{[ $mod->VERSION ]}\n\n”;
}
}
print “Module Testing Done!\n”;
[/perl]
Note: If you are putting module name dynamically, then use @{[ $mod->VERSION ]} for version number
else $Module-Name::VERSION ex: $SOAP::Lite::VERSION
[perl]
print “SOAP::Lite Version is “. $SOAP::Lite::VERSION.”\n”;
#or
print “$mod version is @{[ $mod->VERSION ]} \n”;
[/perl]
4. To list Perl modules that comes preinstalled with the standard Perl package and installed from outside
[perl]
perldoc perlmodlib #lists all the modules that come with standard Perl package already
perldoc perllocal #lists all modules that is installed from outside
[/perl]
Both modules reveal lots of information about each installed modules like installation date, directory, module version etc.
It happens many times that you declare a variable name something and calling that variable name by something else. In case of hash in perl, calling that variable or assigning that variable will not give error. It will silently create that key value pair. This is called autovivification.
For ex:
my $name = "Jassi";
$self->{name} = "Sanjeev aka Jassi" # it will work as it is
$self->{Name} = "Jaiswal"; # It will silently create another key value pair.
# Now if you try to access $self->{name}, it will not give you
#Jaiswal. You will get "Sanjeev aka Jassi".
At above example you can see that our motto was to change the value of key “name” but by mistake we wrote “Name”, then also it got updated without any error. So being a human being, we do such typo mistakes and It will be very tough for us to find such bugs.
Before writing a program, lets keep in mind that what variables we are going to use and strict the program to use those variable name only. If I use any other variable than provided one, it should throw error. For this purpose we use “field” pragma.
#!c:/strawberry/perl/bin/perl.exe
{
package Student;
# You may like to give a list of attributes that are only allowed, and have Perl should exit with an error,
#if someone uses an unknown attribute.
# You can do this using the fields pragma i.e use fields fieldname1, fieldname2 etc"
# Isn't it nice feature to secure our code.
use fields 'name',
'registration',
'grades';
sub new {
my($class, $name) = @_;
$self = fields::new($class); # returns an empty "strict" object
$self->{name} = $name; # attributes get accessed as usual
return $self; # $self is already blessed
}
}
my $classname = Student->new('Jassi');
$classname->{name} = 'Jassi D\'Costa'; # works
$classname->{Name} = 'foo'; # blows up. If I will not use field pragma, It will silently create this key value pair
# for $classname object.
# End of the program
Here is the screen-shot of the error that you will get.
Determining the length of an array and a hash
If you are working on Perl, then you will need to find the length or size of an array, hash, and array/hash elements very often.
Meaning of Size or length depends upon for which context you are talking about. Generally it means the number of characters in a string, or the number of elements in an array/hash.
But, if you are using Unicode characters then the number of characters in a string may be different to the number of bytes in the string. So the in-built function length may give different result for different context.
We will see it by using different examples based on different problems:
Example 1. Finding length() of string
To determine the number of characters in an expression use the length() function:
[perl]#!/usr/bin/perl
use strict;
use warnings;
my $name = 'Jassi';
my $size = length($name);
print "$size\n";
exit 0;[/perl]
This example prints the number of characters in the string $name:
5
Example 2. Find the bytes used by string using length()
What, if you want to know the bytes occupied by the string not the characters it holds? This may not matter if you are using ASCII characters but it may, if you are using Unicode characters.
By default the length() function returns the number of characters. You can tell it to return the number of bytes by specifying use bytes; in the program as in this example:
[perl] #!/usr/bin/perl
use strict;
use warnings;
my $char = "\x{263a}"; # A smiley face
{
use bytes;
my $byte_size = length($char);
print "Bytes: $byte_size\n";
no bytes;
}
# Character size here
my $size = length($char);
print "Chars: $size\n";
exit 0;[/perl]
This outputs:
Bytes: 3
Chars: 1
Note: either use closure or whenever you use “use bytes” try to use “no byets” once you are done
Number of element in an array
Example 3: using array’s last index
In Perl you can determine the last element of an array easily ($#array_name) and add 1 to it to find the number of elements in that array.
[perl] #!/usr/bin/perl
use strict;
use warnings;
my @alien_members = qw(jassi Ritesh Ranjan som Santosh);
my $size = $#alien_members + 1;
print "$size\n";
exit 0;[/perl]
This gives us:
5
Example 4. Using scalar context of an array
If you assign an array to a scalar variable, it will return the number of elements of that array:
[perl] #!/usr/bin/perl
use strict;
use warnings;
my @alien_members = qw(jassi Ritesh Ranjan som Santosh);
my $size = @alien_members;
print "$size\n";
exit 0;[/perl]
This gives us:
5
Apart from being confusing to read, this method can lead to some easy mistakes. For example, consider the following program:
[perl] #!/usr/bin/perl
use strict;
use warnings;
my @alien_members = qw(Jassi Ritesh Ranjan som Santosh);
print "@alien_members\n";
print @alien_members."\n";
exit 0;[/perl]
What would you expect it to print?
Each array elements to a new line like
Jassi
Ritesh
Ranjan …
Nope it would print
Jassi Ritesh Ranjan som Santosh
5
When double-quotes included, it treats arrays differently. The double-quotes cause Perl to flatten the array by concatenating the values into a string. So behind the stage, something like this happened.
“Join each array element by space and assign it to a scalar variable. So it became a string.” It is something like $size = “@alien_members”; which will differ from $size = @alien_members;
try to print these two statements and see the difference.
But check second print output. Isn’t it strange?
Example 5. Arrays: never use length() to find the number of elements in an array.
You have seen the use of length at Example#1 but still If you try to use the length() function on an array, it won't give you the desired output.
[perl]#!/usr/bin/perl
use strict;
use warnings;
my @alien_members = qw(Jassi Ritesh Ranjan som Santosh);
my $size = length(@alien_members);
print "$size\n";
exit 0;[/perl]
The output is not what you thought:
1
This is because the length() function requires a scalar, so the array is forced into scalar context.
And we saw already (example 4) that an array in scalar context already gives us the length. The example above is giving us the length of the length i.e. the length of 5 is 1. Hope it makes sense!
Example 6. Finding the number of elements using scalar() function
No doubt that Example 3 and 4 are correct but they aren't much clear and friendly to use in our program (readability problem you can say). Perl has the scalar() function which forces the array into scalar context which will give you the length of an array (even hash too):
[perl] #!/usr/bin/perl
use strict;
use warnings;
my @alien_members = qw(Jassi Ritesh Ranjan som Santosh);
my $size = scalar(@alien_members);
print "$size\n";
exit 0;[/perl]
This also gives us the correct answer:
5
Example 7. Finding the number of elements in a hash
Sometimes you will also want to have the number of elements of a hash. This is easily done using the keys() function to return the keys as an list, and the scalar() function to return how many keys there are (it is very common question in interviews too):
[perl] #!/usr/bin/perl
use strict;
use warnings;
my %alien_members_rank = (
Jassi => 1,
Ritesh => 2,
Ranjan => 3,
Somnath => 5,
Santosh => 4
);
my $size = scalar(keys %alien_members_rank);
print "$size\n";
exit 0;[/perl]
The output of this program is:
5
Note: it will not give 10 as you might have thought in context of an array. It can give you no of keys elements and then you can just multiply it by 2 😀
For more details on these functions, see also
perldoc -f length
perldoc -f scalar
perldoc bytes