Professional Documents
Culture Documents
1. Write a perl script which, ask the user to enter numbers when executed and then
calculate average of the numbers. [2]
Ans - print "enter numbers\n";
@num = <STDIN>;
$li = $#num;
$t = $li+1;
print "total numbers entered = $t\n";
for($i=0; $i<=$li; $i++)
{
$sum = $sum+$num[$i];
}
print "sum = $sum\n";
$avg = $sum/$t;
print "average = $avg\n";
2. How can you define my variables scope in Perl and how it is different from local
variable scope? [2]
3. Where the command line arguments are stored and if you want to read command-line
arguments with Perl, how would you do that? [1]
Ans - In @ARGV. To read file handle is used <ARGV>.
4. There are some duplicate entries in an array and you want to remove them. How would
you do that? [2]
Ans - print "enter numbers\n";
@num = <STDIN>;
$li = $#num;
}
print "duplicate no. =@dup\n";
5. Explain what is Chop & Chomp function does? [1]
6. Which function is used to identify how many characters are there in a string? [1]
Length ($x)
7. You want to empty an array. How would you do that? [2]
@x =()
Perl Test
1. Describe two ways to concatenate strings in perl. Contrast and compare. 1
Ans – using concatenation operator – ($x.$y)
Using split and join function – split to split strings to array and then join to join the arrays to a
string.
2. How do you replace a character in a string and how do you store the no. of replacements? 1
Ans - print "arr = @ARGV\n";
foreach $val(@ARGV)
{
if($val =~ s/H/I/g)
{
$c+= 1;
}
else
{}
}
print "count = $c\n";
print "subs = @ARGV\n";
3. Write a program to remove trailing blanks and tabs from each of line of input and to delete
entirely blank lines. 2
Ans - open($fh,'<',"f1.txt");
while(<$fh>)
{
$_=~ s/\t/ /g | $_=~ s/\s\s\s*/ /g | $_=~ s/\s$/\n/g;
print ;
}
4. Write a program to remove all comments from a c program. Don’t forget to handle quoted strings
and character constants properly. 2
5. Write a simple regular expression to match an IP address, website, email address, city –state-
zipcode combination. 3
7. In perl, how would you allow functions to have private variables that retain their values from call
to call? 1
Ans - my and local variables are used.
8. Write a program that prints only the lines of its input which contain a certain word. 2
Ans – if( $x=~ /hello/)
Print $x;
9. Predict the output of the following code: 1
my @a = (0,1,2);
my $b = @a;
print $b;
Ans – length of @a means 3.
10. Write a script to reverse string without using perl built in function. 2
Ans - print "enter text\n";
$x = <STDIN>;
@y = split(/ /,$x);
$len = @y;
print "arr =@y\n";
print "cnt =$len\n";
print "el =$y[1]\n";
$le = $#y;
print "le =$y[$le]\n";
11. Write a Perl subroutine that takes a text string as input parameter and returns the frequency of
occurrences of various words in the text as a hash. 3
12. Write Perl statements using regular expressions for the following: 6