Conditional Statements:
Ruby If-else Statement
The Ruby if else statement is used to test conditions. There are various types of if
statements in Ruby.
❖ if statement
❖ if-else statement
❖ if-else-if (elsif) statement
if statement:
The most straightforward of the conditionals is if. In its simplest form, it looks like this:
if expression
code
end
The code between if and end is executed if (and only if) the expression evaluates to
something other than false or nil. The code must be separated from the expression
with a newline or semicolon or the keyword then.
Example:
puts "Enter the age"
a=[Link].to_i
if a>18
puts "Your are eligible for vote"
end
if-else statement:
Ruby if else statement tests the condition. The if block statement is executed if condition
is true otherwise else block statement is executed.
Example:
puts "Enter the age"
a=[Link].to_i
if a>18
puts "Your are eligible for vote"
else
puts "Your are not eligible for Vote"
end
if else if (elsif):
Ruby if else if statement tests the condition. The if block statement is executed if the
condition is true otherwise the else block statement is executed.
Example:
puts "Enter the Percentage"
per=[Link].to_i
if per<40
puts "Failed"
elsif per>=40 and per<50
puts "Passed"
elsif per>=50 and per<60
puts "Average"
else
puts "Good"
end
if As a Modifier:
❖ Used for concise conditional execution in a single line.
❖ Syntax: code if condition (code comes first, then the condition).
❖ The condition is evaluated first, even though written last.
❖ If the condition is anything other than false or nil, the code is executed, and its
value becomes the return value.
❖ If the condition is false or nil, the code is not executed, and the return value is nil.
❖ No else clause is allowed with modifiers
Example:
a=10
puts "This is if modifier" if a==10
unless:
unless, as a statement or a modifier, is the opposite of if: it executes code only if an
associated expression evaluates to false or nil. Its syntax is just like if, except that
elsif clauses are not allowed.
Syntax:
# single-way unless statement
unless condition
code
end
# two-way unless statement
unless condition
code
else
code
end
# unless modifier
code unless condition
Example:
puts "Enter the value"
a=gets.to_i
unless a<5
puts "unless block is executed if condition is false"
else
puts "else block is executed if condition is true"
end
case:
case statement provides a way to handle multiple conditions in a more readable manner
compared to nested if statements.
In other languages like java we use switch in ruby we use case
In other languages like java we use case in ruby we use when
In other languages like java we use default in ruby we use else
Example:
puts "Enter the grade"
grade=gets.to_i
case grade
when 90..100
puts "Excellent"
when 80..89 then puts "Very Good"
when 70..79;
puts "Good"
when 60..69
puts "Average"
else
puts "Keep practicing"
end
Loops:
while and until:
while:
A while loop in Ruby is a control flow construct that repeatedly executes a block of code
as long as a certain condition remains true. It's useful when you don't know beforehand
how many times you need to loop.
Syntax:
while condition
# code to be executed
end
Example:
a=0 a=0
while a<5 while a<5 do
puts "the value of a is #{a}" puts "the value of a is #{a}"
a=a+1 a=a+1
end end
Above two programs gets same output
until:
The until loop is the reverse. The condition is tested and the body is executed if the
condition evaluates to false or nil. This means that the body is executed zero or more
times while the condition is false or nil.
Syntax:
until condition
# code to be executed
end
Example:
Below all the programs get same output
a=10 a=10 a=10
until a<5 until a<5 do until a<5;
puts "The value of puts "The value of puts "The value of
a is #{a}" a is #{a}" a is #{a}"
a=a-1 a=a-1 a=a-1
end end end
begin - end - while / until (like do while in other languages):
There is a special-case exception to this rule. When the expression being evaluated is
a compound expression delimited by begin and end keywords, then the body is executed
first before the condition is tested:
x = 10 # Initialize loop variable
begin # Start a compound expression: executed at least once
puts x # output x
x = x - 1 # decrement x
end until x == 0 # End compound expression and modify it with a loop
This results in a construct much like the do/while loop of C, C++, and Java. Despite
its similarity to the do/while loop of other languages,
for loop:
A for loop in Ruby is a control flow construct that iterates over a collection of elements,
executing a block of code for each element. It's ideal when you know exactly how many
times you need to loop or want to iterate over elements in a sequence.
Syntax:
for element in expression
# code to be executed for each element
end
Example:
for i in 1..5
puts "the value of i is #{i}"
end
Lab Program 4:
Write a Ruby script to accept a filename from the user print the extension of that.
Program:
puts "Enter a filename: "
filename = [Link]
if [Link]?
puts "Error: Please enter a filename."
else
extension = [Link](filename)
end
if [Link]?
puts "The file has no extension."
else
puts "The extension of the file is: #{extension}"
end
Lab Program 5:
Write a ruby script to find greatest of 3 numbers.
Program:
puts "Enter the First number"
x=[Link].to_i
puts "Enter the second number"
y=[Link].to_i
puts "Enter the third number"
z=[Link].to_i
if x>y and x>z
puts "#{x} is the greatest of three number"
elsif y>x and y>z
puts "#{y} is the greatest of three number"
else
puts "#{z} is the greatest of three number"
end
Lab Program 6:
Write a Ruby script to print odd numbers from 10 to 1
puts "Odd Numbers from 10 to 1 are...!"
counter = 9
while counter >= 1
puts counter
counter -= 2
end
Lab Program 7:
Write a Ruby scirpt to check two integers and return true if one of them is 20
otherwise return their sum.
Program:
def makes20(x, y)
if x==20 || y==20
return true
else
return x+y
end
end
puts "Enter the first integer:"
a = [Link].to_i
puts "Enter the second integer:"
b = [Link].to_i
result = makes20(a,b)
puts result
Lab Program 8:
Write a Ruby script to check two temperatures and return true if one is less than 0
and the other is greater than 100
Program:
def temp(temp1,temp2)
if((temp1<0 && temp2>100) || (temp1>100 && temp2<0))
return true
else return false
end
end
puts "Enter the temp1"
a=gets.to_f
puts "Enter the temp2"
b=gets.to_f
result=temp(a,b)
puts result
Arrays:
arrays are ordered collections of elements that can hold various data types. They are a
fundamental data structure used to store and manage lists of items.
Arrays are dynamic, meaning their size can grow or shrink as you add or remove
elements.
Arrays can hold elements of mixed data types (strings, numbers, booleans, even other
arrays).
Ruby provides many built-in methods for working with arrays, like sort, reverse, push,
pop, include?, etc., for various operations.
Creating Arrays:
1. Square brackets: The most common way is using square brackets [] to enclose a
comma-separated list of elements.
Example:
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4]
2. [Link] method: You can create an empty array using the [Link] method with an
optional size argument.
Example:
empty_array = [Link]
fixed_size_array = [Link](5)
Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1,
and so on.
You can access elements using their index within square brackets.
fruits = ["apple", "banana", "orange"]
first_fruit = fruits[0] # "apple"
last_fruit = fruits[2] # "orange"
Sample program on arrays:
rollnos=[10,20,30]
for i in rollnos
puts i
end
Lab Program 9:
Write a Ruby script to print the elements of a given array
Program:
Elements=["Dev",101,"Kits College",50.2]
for a in Elements
puts a
end
Hashes:
A hash is a data structure that maintains a set of objects known as keys, and associates a
value with each key. Hashes are also known as maps because they map keys to values.
They are sometimes called associative arrays because they associate values with each of
the keys, and can be thought of as arrays in which the array index can be any object
instead of an integer.
Example1 :
person = {"name" => "Raju", "age" => 30, "city" => "Hyd"}
Or
person = { :name => "Raju", :age => 30, :city=> "Hyd" }
Example 2:
numbers = [Link] # Create a new, empty, hash object
numbers["one"] = 1 # Map the String "one" to the Fixnum 1
numbers["two"] = 2 # Note that we are using array notation here
numbers["three"] = 3
Lab Program 10:
Write a Ruby program to retrieve the total marks where subject name and marks of
a student stored in a hash
Program:
Both Programs get the same Output:
students=[Link] students={"SL"=>85,"CD"=>95,"M
students["SL"]=85 L"=>100}
students["CD"]=95 total_marks=0
students["ML"]=100 for subject,marks in students
total_marks=0 total_marks=total_marks+marks
for subject,marks in students end
total_marks=total_marks+marks puts total_marks
end
puts total_marks
Output:
Iterators:
iterators are objects that provide a concise and powerful way to loop through collections
of data like arrays, hashes, strings, and more. They offer a flexible alternative to
traditional for loops and enhance code readability.
Methods:
Times method:
Example:
[Link] { puts "thank you!" }:
[Link] is an iterator method that calls the block ({ puts "thank you!" }) three times.
Inside the block, yield (implicit in times) passes control to the block for each iteration.
The block simply prints "thank you!"
Output:
each method:
Example:
data=[10,20,30]
[Link] {|x| puts x }
[Link] is another iterator method that iterates over each element (x) in the collection
data. yield (implicit in each) hands over control to the block for each element. The block
receives the current element (x) and prints it.
map method:
Example:
[1,2,3].map{|x| puts x*x}
[1,2,3].map is an iterator that applies the block to each element and creates a new array
with the results.
yield (implicit in map) passes control to the block for each element (x).
The block squares the current element (x) by multiplying it by itself (x * x) and the result
is added to the new array.
upto method:
Example:
factorial = 1
[Link](5) {|x| puts factorial *= x }
[Link](n) is an iterator that iterates from 2 up to n (inclusive).
yield (implicit in upto) passes control to the block for each number (x) in the iteration.
The block multiplies the current factorial value (factorial) by the current number (x) and
stores the result back in factorial.
[Link] {|x| print x } # => prints "012"
In general, [Link] is equivalent to [Link](n-1).
downto:
downto is a method available on numerical objects (such as integers) that allows you to
iterate downwards from a starting number to a specified limit, executing a block of code
for each iteration.
Example:
[Link](1) do |i|
puts i
end
Output:
5
4
3
2
1
yield:
yield keyword is used to call a block that is passed to a method.
Example:
def call_block
puts "Start of method"
yield
yield
puts "End of method"
end
call_block { puts "In the block" }
Output:
Start of method
In the block
In the block
End of method
PERL PROGRAMS
INTRODUCTION:
Perl(Practical Extraction and Reporting Language) is a high-level, interpreted programming
language known for its versatility and powerful text processing capabilities. Developed by Larry
Wall in the late 1980s, Perl has since become popular among system administrators, web
developers, and software engineers for its robustness and flexibility.
Features:
1. Practicality: Perl was designed with the philosophy of "making easy things easy and hard
things possible." It offers a rich set of built-in functions and libraries for tasks such as file
I/O, regular expressions, and networking, making it well-suited for a wide range of
applications.
2. Text Processing: Perl excels at text manipulation and processing, with native support for
regular expressions and string handling. This makes it particularly useful for tasks such as
parsing data, extracting information from files, and generating reports.
3. Platform Independence: Perl is available on most operating systems, including
Unix/Linux, macOS, and Windows, making it highly portable and suitable for cross-
platform development.
4. Extensibility: Perl supports modular programming and encourages code reuse through its
extensive library of modules available from the Comprehensive Perl Archive Network
(CPAN). Developers can easily extend Perl's functionality by installing and importing
these modules into their projects.
5. Flexibility: Perl's syntax is flexible and expressive, allowing developers to write concise
and readable code. It supports both procedural and object-oriented programming
paradigms, as well as functional programming constructs.
6. Community and Support: Perl has a vibrant and active community of users and
contributors who provide resources, documentation, and support through online forums,
mailing lists, and IRC channels.
Uses of Perl Language:
1. Text processing: Perl is well-suited for text manipulation tasks such as parsing,
searching, and transforming large volumes of text data. It provides powerful regular
expression support, making it ideal for tasks like data extraction, file processing, and log
file analysis.
2. System administration: Perl is frequently used for system administration tasks such as
automating repetitive tasks, managing configuration files, and monitoring system
resources. Its rich set of built-in functions and modules simplifies system-level scripting.
3. Web development: Perl has been used extensively for web development, particularly in
the early days of the web. It can handle tasks such as CGI scripting, server-side scripting,
and web scraping. While its usage in web development has declined with the rise of other
technologies, Perl remains a viable option for certain web applications.
4. Network programming: Perl provides robust support for network programming,
allowing developers to create applications for tasks such as socket programming, network
monitoring, and communication protocols. Its socket modules enable developers to build
client-server applications and network utilities.
5. Bioinformatics: Perl is widely used in the field of bioinformatics for processing
biological data, analyzing DNA sequences, and building bioinformatics tools and
pipelines. Its text processing capabilities and extensive library of bioinformatics modules
make it a popular choice among bioinformaticians.
6. Automation and scripting: Perl is often used for automating tasks and writing scripts
for various purposes, including file manipulation, data transformation, and system
automation. Its expressive syntax, flexible data structures, and comprehensive standard
library make it well-suited for scripting tasks in diverse environments.
Lab Program 11a:
Write a Perl script to find the largest number among three numbers.
Program:
my $num1 = 10;
my $num2 = 20;
my $num3 = 5;
my $largest;
if ($num1 > $num2) {
$largest = $num1;
} elsif ($num2 > $num3) {
$largest = $num2;
} else {
$largest = $num3;
}
print "The largest number is: $largest\n";
Lab Program 11b:
Write a Perl script to print the multiplication tables from 1-10 using subroutines.
sub table
{
my $num = shift;
print "Multiplication table for $num:\n";
for($i=1;$i<=10;$i++)
{
my $result = $num * $i;
print "$num x $i = $result\n";
}
print "\n";
}
for($a=1;$a<=10;$a++) {
table($a);
}
Lab Program 12(a):
Write a Perl program to implement the following list of manipulating functions
a) shift:
shift function is used to remove and return the first element of an array.
Example:
my @array = (1, 2, 3, 4, 5);
my $first_element = shift @array; # Remove and return the first element
print "First element: $first_element\n"; # Output: First element: 1
Explanation:
In this example, @array contains the elements (1, 2, 3, 4, 5). When shift @array is called, it
removes the first element (1) from @array and assigns it to the variable $first_element. After this
operation, @array contains (2, 3, 4, 5).
The shift function modifies the original array by removing the first element. If the array is empty,
shift returns undef.
Program:
my @array = (1, 2, 3, 4, 5);
my $first_element = shift @array;
print "First element: $first_element\n";
print "Updated array: @array\n";
Lab Program 12(b):
unshift:
unshift function is used to add one or more elements to the beginning of an array.
Example -1:
my @array = (2, 3, 4, 5);
unshift @array, 1; # Add 1 to the beginning of the array
print "Updated array: @array\n";
Output:
Example -2:
my @array = (4, 5);
unshift @array, 1, 2, 3; # Add multiple elements to the beginning of the array
print "Updated array: @array\n";
Output:
Lab Program 12(c):
push:
push function is used to add one or more elements to the end of an array.
Example:
my @array = (1, 2, 3, 4);
push @array, 5; # Add 5 to the end of the array
print "Updated array: @array\n"; # Output: Updated array: 1 2 3 4 5
Explanation:
In this example, @array initially contains the elements (1, 2, 3, 4). When push @array, 5 is
called, it adds 5 to the end of the array. After this operation, @array contains (1, 2, 3, 4, 5).
❖ The push function modifies the original array by adding elements to the end. It can also add
multiple elements at once:
Example:
my @array = (1, 2, 3);
push @array, 4, 5, 6; # Add multiple elements to the end of the array
print "Updated array: @array\n";
Output:
13. a) Write a Perl script to substitute a word, with another word in a string
Program:
$str="This is Deepak";
print "Before substitute the string is $str\n";
$str=~s/Deepak/Karthik/;
print "After substitution the string is $str";
Output:
Lab Program 13(b):
Write a Perl script to validate IP address and email address.
Program:
IP Address:
sub ip
{
print "Enter an IP address to validate: ";
chomp(my $input = <STDIN>);
if ($input =~ /([1-9][0-9]{0,2}|0)\.([1-9][0-9]{0,2}|0)\.([1-9][0-9]{0,2}|0)\.([1-9][0-9]{0,2}|0)/)
{
if(($1>=0 && $1<=255)&&($2>=0 && $2<=255)&&($3>=0 && $3<=255)&&($4>=0 &&
$4<=255) )
{
print "Valid IP Address";
}
else
{
print "Invalid IP Address";
}
}
else
{
print "Invalid IP Address";
}
}
ip();
Output:
Mail Id:
sub mail
{
print "Enter the mail id";
chomp($id=<STDIN>);
if($id=~/[a-zA-Z][a-zA-Z0-9]*@[a-zA-Z0-9]+\.[a-zA-Z]+/)
{
print "valid Mail id"
}
else
{
print "Invalid mail id";
}
}
mail();
Output:
14. Write a Perl script to print the file in reverse order using command line arguments
Program:
my $filename = $ARGV[0];
open my $fh, '<', $filename;
@lines = <$fh>;
close $fh;
print reverse @lines;
Output: