0% found this document useful (0 votes)
655 views39 pages

SL Lab Manual

The document provides examples of Ruby, Tcl, Perl, and shell scripts that demonstrate common programming tasks like string manipulation, math operations, conditional logic, arrays, hashes, file operations, and more. Some key examples include a Ruby program to multiply a string, a Tcl script to calculate a factorial, and Perl scripts to compare numbers, print multiplication tables with subroutines, and demonstrate list manipulation functions like shift, unshift, push, and pop.

Uploaded by

Bhanu sree Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
655 views39 pages

SL Lab Manual

The document provides examples of Ruby, Tcl, Perl, and shell scripts that demonstrate common programming tasks like string manipulation, math operations, conditional logic, arrays, hashes, file operations, and more. Some key examples include a Ruby program to multiply a string, a Tcl script to calculate a factorial, and Perl scripts to compare numbers, print multiplication tables with subroutines, and demonstrate list manipulation functions like shift, unshift, push, and pop.

Uploaded by

Bhanu sree Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

1.

Write a Ruby program to create a new string which is n copies of a


given string where n is a non-negative integer.

def multiple_string(str, n)
return str*n
end
print multiple_string('a', 1),"\n"
print multiple_string('a', 2),"\n"
print multiple_string('a', 3),"\n"
print multiple_string('a', 4),"\n"
print multiple_string('a', 5),"\n"

Output:

a
aa
aaa
aaaa
aaaaa

1
2. Write a Ruby program which accept the radius of a circle from
the user and compute the perimeter and area.

radius = 5.0
perimeter = 0.0
area = 0.0
print "Input the radius of the circle: "
radius = gets.to_f
perimeter = 2 * 3.141592653 * radius
area = 3.141592653 * radius * radius
puts "The perimeter is #{perimeter}."
puts "The area is #{area}."

Output:

Input the radius of the circle: The perimeter is 31.41592653.


The area is 78.539816325.

2
3. Write a Ruby program which accept the user's first and last
name and print them in reverse order with a space between
them.

puts "Input your first name: "


fname = gets.chomp
puts "Input your last name: "
lname = gets.chomp
puts "Hello #{lname} #{fname}"

Output:
Input your first name:Smitha
Input your last name: Singh
Hello Smitha Singh

3
4. write a ruby script to accept a filename from the user and print the
extension of that

file = "/user/system/test.rb"
# file name
fbname = File.basename file
puts "File name: "+fbname

4
# basename
bname = File.basename file,".rb"
puts "Base name: "+bname
# file extention
ffextn = File.extname file
puts "Extention: "+ffextn
# path name
path_name= File.dirname file
puts "Path name: "+path_name

Output:
File name: test.rb
Base name: test
Extention: .rb
Path name: /user/system

5
5. Write a Ruby program to find the greatest of three numbers.

x,y,z = 2,5,4
if x >= y and x >= z
puts "x = #{x} is greatest."
elsif y >= z and y >= x
puts "y = #{y} is greatest."
else
puts "z = #{z} is greatest."
end

Output:
y = 5 is greatest.

6
6. Write a Ruby program to print odd numbers from 10 to 1.

puts "Odd numbers between 9 to 1: "


9.step 1, -2 do |x|
puts "#{x}"
end

Output:
Odd numbers between 9 to 1:
9
7
5
3
1

7
7. Write a Ruby program to check two integers and return true if one
of them is 20 otherwise return their sum.

def makes20(x,y)
return x == 20 || y == 20 || x + y == 20
end

8
print makes20(10, 10),"\n"
print makes20(40, 10),"\n"
print makes20(15, 20)

Output:

true
false
true

9
8. Write a Ruby program to check two temperatures and return true if
one is less than 0 and the other is greater than 100.

def temp(temp1, temp2)


return ( temp1 < 0 && temp2 > 100 ) || ( temp1 > 100 && temp2 <
0 );
end
print temp(110, -1),"\n"
print temp(-1, 110),"\n"
print temp(2, 120)

Output:
true
true
false

10
9. Write a Ruby program to print the elements of a given array.

array1 = ["Ruby", 2.3, Time.now]


for array_element in array1
puts array_element
end

Output:

Ruby
2.3
2017-12-28 06:01:53 +0000

11
10. Write a Ruby program to retrieve the total marks where subject
name and
marks of a student stored in a hash.

student_marks = Hash.new 0
student_marks['Literature'] = 74
student_marks['Science'] = 89
student_marks['Math'] = 91
total_marks = 0
student_marks.each {|key,value|
total_marks +=value

12
}
puts "Total Marks: "+total_marks.to_s

Output:

Total Marks: 254

11. write a tcl script to find factorial of a number.

13
proc Factorial {x} {
set i 1; set product 1
while {$i <= $x} {
set product [expr $product * $i]
incr i
}
return $product
}
Factorial 10

Output:
3628800

14
12. write a tcl script for sorting a list using a comparison function

%proc compare {a b} {
set a0 [lindex $a 0]
set b0 [lindex $b 0]
if {$a0 < $b0} {
return -1
} elseif {$a0 > $b0} {
return 1
}
return [string compare [lindex $a 1] [lindex $b 1]]
}
% lsort -command compare \
{{3 apple} {0x2 carrot} {1 dingo} {2 banana}}
{1 dingo} {2 banana} {0x2 carrot} {3 apple}

15
13. write a TCL script to (i) create a list (ii) append elements to the
list (iii) Traverse the list (iv) Concatenate the list
(i)
#!/usr/bin/tclsh

set l1 { 1 2 3 }
set l2 [list one two three]
set l3 [split "1.2.3.4" .]

puts $l1
puts $l2
puts $l3

Output:
123
one two three
1234

16
(ii)
#!/usr/bin/tclsh

set var orange


append var " " "blue"
lappend var "red"
lappend var "green"
puts $var

Output:
orange blue red green

(iii)

foreach i { red green blue } {


puts $i
}

Output:
Red
Green
Blue

17
(iv)
Set first { red green blue}
Set second {pink yellow brown}
Concat $first $second
Puts $first

18
14. write a TCL script for comparing the file modified times.

source_file=foo;
target_file=bar;
stat_source=$(stat source_file);
stat_target=$(stat target_file);
if [ "$source_file" -nt "$target_file" ]
then
printf '%s\n' "$source_file is newer than $target_file"
fi

19
15. a. write a PERL script to find the largest number among three
numbers

#!/usr/bin/perl
print "enter a value";
$x=<stdin>;
print "enter b value";
$y=<stdin>;
print "enter c value";
$z=<stdin>;
if($a > $b) //if compares string use gt ,lt,le,ge
{
if($a> $c)
{
print " $a is largest number\n";
}
else
{
print " $c is largest number\n";
}
}
elsif($b >$c)
{
print " $b is largest number";

20
}
else
{
print " $c is largest nnumber";
}

OUT PUT:

Perl great.pl

Enter a value 4
Enter b value 6
Enter c value 5
6 is largest number

16. b. write a PERL script to print the multiplication tables from 1-


10 using subroutines.
use strict;
use warnings;
use diagnostics;
use 5.01000;

&table(1,2,3,4,5,6,7,8,9,10);

sub table {
21
my $i = 1;
my $loop;

foreach $loop (@_) {


warn " loop $loop \n";
for ( $i ; $i <= 10 ; $i++ ) {
my $ans = $i * $loop;
print "$ans ";
}
print "\n";
}
}

22
17. write a PERL program to implement the following list
manipulation functions
a. shift b. unshift c. push

a. shift
This function returns the first value in an array, removing it and
shifting the elements of the array list to the left by one. Shift
operation removes the value like pop but is taken from the start
of the array instead of the end as in pop. This function returns
undef if the array is empty otherwise returns first element of the
array.
Syntax: shift(Array)

#!/usr/bin/perl
  
# Initalizing the array
@x = ('Java', 'C', 'C++');
  
# Print the Inital array
print "Original array: @x \n";
  
# Prints the value returned
# by shift function
print "Value returned by shift: ", shift(@x);
  
# Array after shift operation
print "\nUpdated array: @x";

Output:

Original array: Java C C++


Value returned by shift :Java
Updated array: C C++
23
b. unshift

This function places the given list of elements at the beginning


of an array. Thereby shifting all the values in an array by right.
Multiple values can be unshift using this operation. This
function returns the number of new elements in an array.

Syntax: unshift(Array, List)

#!/usr/bin/perl
  # Initalizing the array
@x = ('Java', 'C', 'C++');

# Print the Inital array


print "Original array: @x \n";
  
# Prints the number of elements
# returned by unshift
print "No of elements returned by unshift: ",
   unshift(@x, 'PHP', 'JSP');
24
  
# Array after unshift operation
print "\nUpdated array: @x";

Output:

Original array: Java C C++


No of elements returned by unshift :5
Updated array: PHP JSP Java C C++

c. push

This function inserts the values given in the list at an end of an


array. Multiple values can be inserted separated by comma. This
function increases the size of an array. It returns number of
elements in new array.

Syntax: push(Array, list)

#!/usr/bin/perl
25
  
# Initalizing the array
@x = ('Java', 'C', 'C++');
  
# Print the Inital array
print "Original array: @x \n";
  
# Pushing multiple values in the array
push(@x, 'Python', 'Perl');
  
# Printing the array
print "Updated array: @x";

Output:

Original array: Java C C++


Updated array: Java C C++ Python Perl

26
d. pop
This function is used to remove the last element of the array.
After executing the pop function, size of the array is
decremented by one element. This function returns undef if list
is empty otherwise returns the last element of the array.
Syntax: pop(Array)

#!/usr/bin/perl
  
# Initalizing the array
@x = ('Java', 'C', 'C++');
  
# Print the Inital array
print "Original array: @x \n";
  
# Prints the value returned by pop
print "Value returned by pop: ", pop(@x);
  
# Prints the array after pop operation
print "\nUpdated array: @x";

Output:

Original array: Java C C++


Value returned by pop: C++
Updated array: Java C

27
18. a. write a PERL script to substitute a word , with another word
in a string.

(i)
my $old = 'cat';
my $new = $old =~ s/cat/dog/r;

(ii)

my $string = "Tea is good with milk.";

$string =~ s/tea/coffee/ig;

print $string;

Output:
coffee is good with milk.

b. Write a PERL script to validate IP address and Email address.


28
#!/usr/bin/perl
use strict;
use warnings;
print("What is the IP Address you would like to validate: ");
my $ipaddr = <STDIN>;
chomp($ipaddr);
if( $ipaddr =~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/ )
{
print("IP Address $ipaddr --> VALID FORMAT! \n");
 
if($1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255)
{
print("IP address: $1.$2.$3.$4 --> All octets within range\
n");
}
else
{
print("One of the octets is out of range. All octets must
contain a number between 0 and 255 \n");
}
}
else
{
print("IP Address $ipaddr --> NOT IN VALID FORMAT! \
n");
}

Email::Address can be used to extract a list of e-mail addresses from a


given string. For example:

use strict;
use warnings;
use 5.010;
 
use Email::Address;
 

29
my $line = '[email protected] Foo Bar <[email protected]> Text
[email protected] ' ;
 
my @addresses = Email::Address->parse($line);
foreach my $addr (@addresses) {
say $addr;
}

Output:

[email protected]
"Foo Bar" <[email protected]>
[email protected]

Email::Valid can used to validate if a given string is indeed an e-mail


address:

use strict;
use warnings;
use 5.010;
use Email::Valid;
 
 
foreach my $email ('[email protected]', ' [email protected] ', 'foo at
bar.com') {
my $address = Email::Valid->address($email);
say ($address ? "yes '$address'" : "no '$email'");
}
 

Output:
yes '[email protected]'
yes '[email protected]'
no 'foo at bar.com'

30
19. Write a PERL script to print the file in reverse order using
command line arguments.

if [ $# -eq 1 ]
then
if [ -f $1 ]
then
a=`rev $1`
echo "Reverse of $1"
cat $1
echo " is-> $a"else
echo "File does not exist '
fi
else
echo "Please enter file name or path"
fi

31
20. Write a TCL script that multiplies the numbers from 1 to 10

set n 10
for { set i 1} {$i <= $n} {incr i} {
puts $i

32
Practice Programs

1. Write Ruby program to get ruby version with patch number.

puts "Ruby Version: "+RUBY_VERSION

33
puts "Ruby Patch Level: "+RUBY_PATCHLEVEL.to_s

2. Write a Ruby program to display the current date and time.

require 'date'
current_time = DateTime.now
cdt = current_time.strftime "%d/%m/%Y %H:%M"
puts "Current Date and Time: "+cdt

3.  Write a Ruby program which accept the radius of a circle from


the user and compute the parameter and area. 

radius = 5.0
perimeter = 0.0
area = 0.0
print "Input the radius of the circle: "
radius = gets.to_f
perimeter = 2 * 3.141592653 * radius
area = 3.141592653 * radius * radius
puts "The perimeter is #{perimeter}."
puts "The area is #{area}."

4. Write a Ruby program to check whether a string starts with "if"

def start_if(str)
return str[0, 2] == "if";
end
print start_if("ifelse"),"\n"
print start_if("endif"),"\n"

34
5. a simple Hello World Program.

#!/usr/bin/perl 

    # Modules used 

use strict; 

use warnings; 

 # Print function  

print("Hello World\n"); 

6. PERL program for addition of two numbers

#!/usr/bin/perl
$b = 10;    # Assigning value to $b
$c = 30;    # Assigning value to $c
  
$a = $b + $c;   # Performing the operation
print "$a";     # Printing the result

7. Perl Program to illustrate the Operators 


    
# Operands 
35
$a = 10; 
$b = 4; 
$c = true;
$d = false;
    
# using airthmetic operators  
print "Addition is: ", $a + $b, "\n"; 
print "Subtraction is: ", $a - $b, "\n" ; 
  
# using Relational Operators 
if ($a == $b) 

   print "Equal To Operator is True\n"; 
}  
else 

   print "Equal To Operator is False\n"; 

  
# using Logical Operator 'AND'
$result = $a && $b; 
print "AND Operator: ", $result, "\n"; 
  
# using Bitwise AND Operator 
$result = $a & $b; 
print "Bitwise AND: ", $result, "\n"; 

# using Assignment Operators 


print "Addition Assignment Operator: ", $a += $b, "\n"; 

8. # Perl program to illustrate


# the use of numbers

36
#!/usr/bin/perl
 
# Integer 
$a = 20; 
 
# Floating Number 
$b = 20.5647; 
 
# Scientific value 
$c = 123.5e-10; 
 
# Hexadecimal Number 
$d = 0xc; 
  
# Octal Number 
$e = 074; 
 
# Binary Number 
$f = 0b1010; 
  
# Printing these values 
print("Integer: ", $a, "\n");
print("Float Number: ", $b, "\n"); 
print("Scientific Number: ", $c, "\n"); 
print("Hex Number: ", $d, "\n"); 
print("Octal number: ", $e, "\n"); 
print("Binary Number: ", $f, "\n"); 

9. Perl program to demonstrate  


# scalars variables 
  

37
# a string scalar 
$name = "Alex"; 
    
# Integer Scalar 
$rollno = 13; 
    
# a floating point scalar 
$percentage = 87.65; 
  
# In hexadecimal form 
$hexadec = 0xcd; 
  
# Alphanumeric String
$alphanumeric = "gfg21"; 
  
# special character in string scalar 
$specialstring = "^gfg"; 
  
# to display the result 
print "Name = $name\n"; 
print "Roll number = $rollno\n"; 
print "Percentage = $percentage\n"; 
print "Hexadecimal Form = $hexadec\n"; 
print "String with alphanumeric values = $alphanumeric\n"; 
print "String with special characters = $specialstring\n";

10. # Perl Program for array creation


# and accessing its elements
#!/usr/bin/perl
  
  
# Define an array
@arr1 = (1, 2, 3, 4, 5);
  

38
# using qw function 
@arr2 = qw /This is a Perl Tutorial by GeeksforGeeks/; 
  
# Accessing array elements
print "Elements of arr1 are:\n"; 
print "$arr1[0]\n";
print "$arr1[3]\n";
  
# Accessing array elements
# with negative index
print "\nElements of arr2 are:\n"; 
print "$arr2[-1]\n";
print "$arr2[-3]\n";

39

You might also like