A. Simple
1. Write a Perl script to find and print the longest word in a text file.
2. Implement proactive password checker, means allow a person to enter his password, check for following conditions
- Password should be at least 8 characters in length
- It should contain alphanumeric, upper & lowercase letters
- It should contain any of these special characters @, $ and #.
Solutions
#!/usr/bin/perl -w
#Write a Perl script to find and print the longest word in a text file.
#Importing packages
use strict;
use Getopt::Long;
#Global variables
my ($help, $file);
#Processing command line arguments
GetOptions("h"=>\$help,
"f=s"=>\$file,
);
if($help) {
usage();
}
#Check for -f option
if(!defined($file)){
print "ERROR: -f option is compulsory\n";
usage();
}
open(FH, "$file") || die "Error: Can't open $file: $!";
my ($len,$word,@line,$element);
my $largest=0;
foreach(
{
@line=split(/\s+/,$_);
foreach $element (@line)
{
$len=length($element);
if($len > $largest) {
$largest=$len;
$word=$element;
}
}
}
print "Largest word length is: $largest and the word is $word\n";
sub usage
{
print "USAGE: $0 -f
exit(1);
}
2.
#!/usr/bin/perl -w
## Proactive password checker ##########
use strict;
use Term::ReadKey;
my $user=`whoami`; chomp($user);
print "Hello $user ..\n";
my $try=0;
my $passwd;
accept_password();
sub accept_password
{
$try++;
if($try <= 3)
{
print "Enter your password\n";
ReadMode 'noecho';
$passwd=ReadLine 0;chomp($passwd);
ReadMode 'normal';
check_passwd();
}else
{
print "You exceeded maximum attempts\n";
exit(1);
}
}
sub check_passwd
{
#Check if password length is atleast 8
if(length($passwd) <>
{
print "ERROR: Your password length is less than 8\n";
print "PASSWORD REJECTED\n";
accept_password();
}
#Check for digit
if($passwd =~ /[0-9]/) {
}else{
print "ERROR: No digit in your password\n";
print "PASSWORD REJECTED\n";
accept_password();
}
#Check for lowercase letter
if($passwd =~ /[a-z]/) {
}else{
print "ERROR: No lowercase letter in your password\n";
print "PASSWORD REJECTED\n";
accept_password();
}
#Check for Uppercase letter
if($passwd =~ /[A-Z]/) {
}else{
print "ERROR: No Uppercase letter in your password\n";
print "PASSWORD REJECTED\n";
accept_password();
}
#Check for special characters
#if(($passwd =~ /\@/)|| ($passwd =~ /#/) || ($passwd =~ /\$/)){
if( ($passwd =~ /\@/) || ($passwd =~ /\$/) || ($passwd =~ /\#/) ){
}else{
print "ERROR: No special characters \@ # \$\n";
print "PASSWORD REJECTED\n";
accept_password();
}
}
print "PASSWORD ACCEPTED\n";
No comments:
Post a Comment