0% found this document useful (0 votes)
22 views44 pages

Finalprintsl

Final print need dove intha prifit this go

Uploaded by

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

Finalprintsl

Final print need dove intha prifit this go

Uploaded by

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

SCRIPTING LANGUAGES LAB

1. Write a Ruby script to create a new string which is n copies of a


given string where n is a nonnegative integer

AIM: To write a Ruby script to create a new string which is n copies of a


given string where n is a nonnegative integer.

DESCRIPTION:
Method is a collection of statements that perform some specific task and
return the result. Methods allow the user to reuse the code without retyping
the code.

Defining & Calling the method: In Ruby, the method defines with the help of
def keyword followed by method name and ends with end keyword. A
method must be defined before calling and the name of the method should
be in lowercase.

Method names should begin with a lowercase letter.

Note: You won’t get an immediate error if you use an uppercase letter, but
when Ruby sees you calling the method, it will first guess that it is a
constant, not a method invocation, and as a result it may parse the call
incorrectly.

Syntax:
def method name
# Statement 1
# Statement 2
…..
End

Ruby strings are simply sequences of 8-bit bytes. They normally hold
printable characters, a string can also hold binary data. Strings are objects

1
SCRIPTING LANGUAGES LAB

of class String. Strings are often created using string literals—sequences of


characters between delimiters. you can place various escape sequences in a
string literal. Within single-quoted strings, two consecutive backslashes are
replaced by a single backslash, and a backslash followed by a single quote
becomes a single quote.

'Escape using "\\" '  escape using "\"


'That\'s right'  That's right
Double-quoted strings support a boatload more escape sequences. In
addition, you can substitute the value of any Ruby code into a string
using the sequence #{ expr }.
"Hai Good morning" Hai Good morning
"This is line #$."  This is line 3
There are many ways to print something in Ruby. Here are the most
useful:
1. puts
2. print
3. p
puts: The puts and to display the results of evaluating Ruby code. The puts
adds a newline after executing.
print: If you don’t want a newline, then use print.

p: It is a method that shows a more “raw” version of an object. When you’re


looking for things like (normally invisible) newline characters, or you want to
make sure some value is correct, then you use p.

puts "Ruby Is Cool"


Ruby Is Cool
p "Ruby Is Cool"
"Ruby Is Cool"

2
SCRIPTING LANGUAGES LAB

PROGRAM:

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

3
SCRIPTING LANGUAGES LAB

2. Write a Ruby script which accept the radius of a circle from the user
and compute the parameter and area.
AIM: To write a Ruby script which accept the radius of a circle from the user
and compute the parameter and area.

DESCRIPTION:
Variables are used to keep track of objects; each variable holds a reference
to an object. A variable is simply a reference to an object.
A variable is simply a name for a value. Variables are created and values
assigned to them by assignment expressions. There are four kinds of
variables in Ruby, and lexical rules govern their names. Variables that begin
with $ are global variables, visible throughout a Ruby program. Variables
that begin with @ and @@ are instance variables and class variables, used in
object-oriented programming.And variables whose names begin with an
underscore or a lowercase letter are local variables, defined only within the
current method or block.
PROGRAM:
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: 5
The perimeter is 31.41592653.
The area is 78.539816325.

4
SCRIPTING LANGUAGES LAB

3. Write a Ruby script which accept the user's first and last name and
print them in reverse order with a space between them.
AIM: To write a Ruby script which accept the user's first and last name and
print them in reverse order with a space between them.

DESCRIPTION:
The puts (short for “put string”) and to display the results of evaluating
Ruby code. The puts adds a newline after executing.chomp is the method to
remove trailing new line character i.e. '\n' from the the string. Whenever
"gets" is use to take input from user it appends new line character i.e.'\n' in
the end of the string. So to remove '\n' from the string 'chomp' is used.
chomp is a String class method in Ruby which is used to returns new String
with the given record separator removed from the end of string.

PROGRAM:
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:
SRIKANTH
Input your last name:
NNRG
Hello SRIKANTH NNRG

5
SCRIPTING LANGUAGES LAB

4. Write a Ruby script to accept a filename from the user print the
extension of that.
AIM: To write a Ruby script to accept a filename from the user print the
extension of that.

DESCRIPTION:
Ruby IO has a subclass as File class which allows reading and writing files
in Ruby. The two classes are closely associated. A Ruby file can be created
using different methods for reading, writing or both.
Common modes in I/O port:
"r": read-only mode is the default mode starts at beginning of file.
"r+": read-write mode, starts at beginning of file.
"w": write-only mode, either creates a new file or truncates an existing file for
writing.
"w+": read-write mode, either creates a new file or truncates an existing file
for reading and writing.
"a": write-only mode, if file exists it will append the file otherwise a new file
will be created for writing only.
"a+": read and write mode, if file exists it will append the file otherwise a new
file will be created for writing and reading.
Creating a new file:
We can create a new File using File.new() method for reading, writing or for
both, according to the mode string. We can use fileobject.close() method to
close that file.
Writing to the file
With the help of syswrite method, you can write content into a file. File
needs to be opened in write mode for this method. The new content will over
write the old content in an already existing file.
Syntax:
fileobject = File.new("filename.txt", "mode")
fileobject.syswrite("Text to write into the file")
fileobject.close()

6
SCRIPTING LANGUAGES LAB

PROGRAM:
file = "/user/system/test.rb"
# file name
fbname = File.basename file
puts "File name: "+fbname
# 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
Output:
File name: Rubyprog1.rb
Base name: Rubyprog1
Extention: .rb
Path name: D:/Gee/Gee-RubyPrograms

7
SCRIPTING LANGUAGES LAB

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

AIM: To write a Ruby script to find the greatest of three numbers.

DESCRIPTION:
Ruby if...else Statement:
The Ruby if else statement is used to test condition. There are various types
of if statement in Ruby.
if statement:
Syntax:
if (condition)
//code to be executed
end

if-else statement:
Syntax:
if(condition)
//code if condition is true
else
//code if condition is false
end

if-else-if (elsif) statement:


Syntax:
if conditional [then]
code...
[elsif conditional [then]
code...]...
[else
code...]
end

8
SCRIPTING LANGUAGES LAB

if expressions are used for conditional execution. The values false and nil
are false, and everything else are true. Ruby uses only elsif, not else if nor
elif.
Executes code if the conditional is true. If the conditional is false, code
specified in the else clause is executed.
An if expression's conditional is separated from code by the reserved word
then, a newline, or a semicolon.
ternary (shortened if statement) statement
In Ruby ternary statement, the if statement is shortened. First it evaluats an
expression for true or false value then execute one of the statements.
Syntax:
test-expression ? if-true-expression : if-false-expression
PROGRAM:
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.

9
SCRIPTING LANGUAGES LAB

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

AIM: To write a Ruby script to print odd numbers from 10 to 1.

DESCRIPTION:

Types of Iterators:
 The word iterate means doing one thing multiple times and that is
what iterators do. Sometimes iterators are termed as the custom
loops.
 “Iterators” is the object-oriented concept in Ruby.
 In more simple words, iterators are the methods which are supported
by collections(Arrays, Hashes etc.). Collections are the objects which
store a group of data members.
 Ruby iterators return all the elements of a collection one after another.
 Ruby iterators are “chainable” i.e adding functionality on top of each
other.
 There are many iterators in Ruby as follows:
1. Each Iterator
2. Collect Iterator
3. Times Iterator
4. Upto Iterator
5. Downto Iterator
6. Step Iterator
7. Each_Line Iterator
 Step Iterator: Ruby step iterator is used to iterate where the user
has to skip a specified range.
Syntax:
Collection.step(rng) do |variable_name|
# code to be executed
end

10
SCRIPTING LANGUAGES LAB

 Here rng is the range which will be skipped throughout the iterate
operation.

PROGRAM:

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

11
SCRIPTING LANGUAGES LAB

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

AIM: To write a Ruby script to check two integers and return true if one of
them is 20 otherwise return their sum.

DESCRIPTION:
 Method is a collection of statements that perform some specific task
and return the result. Methods allow the user to reuse the code
without retyping the code.
 Defining & Calling the method: In Ruby, the method defines with
the help of def keyword followed by method_name and ends with end
keyword. A method must be defined before calling and the name of the
method should be in lowercase.
 Method names should begin with a lowercase letter.
 Note: You won’t get an immediate error if you use an uppercase letter,
but when Ruby sees you calling the method, it will first guess that it is
a constant, not a method invocation, and as a result it may parse the
call incorrectly.
Syntax:
def method_name
# Statement 1
# Statement 2
end
 There are many ways to print something in Ruby. Here are the most
useful:
1. puts
2. print
3. p
 puts: The puts and to display the results of evaluating Ruby code.
The puts adds a newline after executing.
 print: If you don’t want a newline, then use print.

12
SCRIPTING LANGUAGES LAB

 p: It is a method that shows a more “raw” version of an object. When


you’re looking for things like (normally invisible) newline characters,
or you want to make sure some value is correct, then you use p.
puts "Ruby Is Cool"
Ruby Is Cool
p "Ruby Is Cool"
"Ruby Is Cool"

PROGRAM:
def makes20(x,y)
return x == 20 || y == 20 || x + y == 20
end
print makes20(10, 10),"\n"
print makes20(40, 10),"\n"
print makes20(15, 20)

OUTPUT:
true
false
true

13
SCRIPTING LANGUAGES LAB

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

AIM: To write a Ruby script to check two temperatures and return true if
one is less than 0 and the other is greater than 100.

DESCRIPTION:
 Method is a collection of statements that perform some specific task
and return the result. Methods allow the user to reuse the code
without retyping the code.
 Defining & Calling the method: In Ruby, the method defines with
the help of def keyword followed by method_name and ends with end
keyword. A method must be defined before calling and the name of the
method should be in lowercase.
 Method names should begin with a lowercase letter.
 Note: You won’t get an immediate error if you use an uppercase letter,
but when Ruby sees you calling the method, it will first guess that it is
a constant, not a method invocation, and as a result it may parse the
call incorrectly.
Syntax:
def method_name
# Statement 1
# Statement 2
end
 There are many ways to print something in Ruby. Here are the most
useful:
1. puts
2. print
3. p
 puts: The puts and to display the results of evaluating Ruby code.
The puts adds a newline after executing.
 print: If you don’t want a newline, then use print.

14
SCRIPTING LANGUAGES LAB

 p: It is a method that shows a more “raw” version of an object. When


you’re looking for things like (normally invisible) newline characters,
or you want to make sure some value is correct, then you use p.
puts "Ruby Is Cool"
Ruby Is Cool
p "Ruby Is Cool"
"Ruby Is Cool"
 The return statement in ruby is used to return one or more values
from a Ruby Method.
PROGRAM:
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

15
SCRIPTING LANGUAGES LAB

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

AIM: To write a Ruby script to print the elements of a given array.

DESCRIPTION:
 An array is a collection of different or similar items, stored at
contiguous memory locations. The idea is to store multiple items of
the same type together which can be referred to by a common name.
 In Ruby, numbers, strings, etc all are primitive types but arrays are of
objects type i.e arrays are the collection of ordered, integer-indexed
objects which can be store number, integer, string, hash, symbol,
objects or even any other array.
 In general, an array is created by listing the elements which will be
separated by commas and enclosed between the square brackets [ ].
 There are several ways to create an array. But there are two ways
which mostly used are as follows:
 Using the new class method: new is a predefined method which can
be used to create the arrays with the help of dot operator. Here new
method with zero, one or more than one arguments is called
internally. Passing arguments to method means to provide the size to
array and elements to array.
Syntax:
name_of_array= Array.new
 Using literal constructor[ ] : In Ruby, [ ] is known as the literal
constructor which can be used to create the arrays. Between [ ],
different or similar type values can be assigned to an array
 There are many ways to print something in Ruby. Here are the most
useful:

16
SCRIPTING LANGUAGES LAB

1. puts
2. print
3. p
 puts: The puts and to display the results of evaluating Ruby code.
The puts adds a newline after executing.
 print: If you don’t want a newline, then use print.
 p: It is a method that shows a more “raw” version of an object. When
you’re looking for things like (normally invisible) newline characters,
or you want to make sure some value is correct, then you use p.
puts "Ruby Is Cool"
Ruby Is Cool
p "Ruby Is Cool"
"Ruby Is Cool"

PROGRAM:
color = ["Red", "Green", "Blue", "White"]
print "Original array:\n"
print color
print "\nCheck if 'Green' in color array!\n"
print color.include? 'Green'
print "\nCheck if 'Pink' in color array!\n"
print color.include? 'Pink'
OUTPUT:
Original array:
["Red", "Green", "Blue", "White"]
Check if 'Green' in color array!
true
Check if 'Pink' in color array!
false

17
SCRIPTING LANGUAGES LAB

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

AIM: To write a Ruby script to retrieve the total marks where subject name
and marks of a student stored in a hash.

DESCRIPTION:
 Hash is a data structure that maintains a set of objects which are
termed as the keys and each key associate a value with it.
 A Ruby hash is a collection of unique keys and their values. They are
similar to arrays but array use integer as an index and hash use any
object type. They are also called associative arrays, dictionaries or
maps.
 The difference between hashes and arrays is that arrays always use
an integer value for indexing whereas hashes use the object.
Syntax:
name = {"key1" => "value1", "key2" => "value2", "key3" => "value3"...}
OR
name = {key1: 'value1', key2: 'value2', key3: 'value3'...}

PROGRAM:

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}
puts "Total Marks: "+total_marks.to_s

OUTPUT:

18
SCRIPTING LANGUAGES LAB

Total Marks: 254


11. Write a TCL script to find the factorial of a number

Aim: To write a TCL script to find the factorial of a number.

Description:

Program:

Output:

Factorial 10

=> 3628800

The semicolon is used on the first line to remind you that it is a command
terminator just like the newline character. The while loop is used to multiply
all the numbers from one up to the value of x. The first argument to while is a
Boolean expression, and its second argument is a command body to execute.

19
SCRIPTING LANGUAGES LAB

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

Aim: To write a TCL script that multiplies the numbers from 1 to 10.

Description:

Program:
# A program that does a loop and prints
# the numbers from 1 to 10
#
set i 1
while {$i <= 10} {
puts $i
incr i
}
Output:
1
2
3
4
5
6
7
8
9
10

20
SCRIPTING LANGUAGES LAB

set num 10
set sum 1
for {set i 1} {$i<=$num} {incr i} {
set sum [expr $sum * $i]
}
puts "The Sum of number $num is $sum"

set num 10
set sum 1
for {set i 1} {$i<=$num} {incr i} {
set sum [expr $sum * $i]
}
puts "The Sum of number $num is $sum"

OUTPUT:

The Sum of number 10 is 3628800

21
SCRIPTING LANGUAGES LAB

13. Write a TCL script for Sorting a list using a comparison function

Aim: To write a TCL script for Sorting a list using a comparison function.

Description:

Program:

1./* More complex sorting 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}
*/
2. lsort ?options? list
-command command
Use command as a comparison command. To compare two elements,
evaluate a Tcl script consisting of command with the two element
appended as additional arguments.

22
SCRIPTING LANGUAGES LAB

14. Write a TCL script to (i)create a list (ii )append elements to the list
(iii)Traverse the
list (iv)Concatenate the list
Aim: To write a TCL script to (i)create a list (ii )append elements to the list
(iii)Traverse the
list (iv)Concatenate the list.
Description:

Program:
i)create a list
#!/usr/bin/tclsh
set colorList1 {red green blue}
set colorList2 [list red green blue]
set colorList3 [split "red_green_blue" _]
puts $colorList1
puts $colorList2
puts $colorList3
Output:
red green blue
red green blue
red green blue
append elements to the list
set a [list a b c]
set b [list 1 2 3]
append a $b
puts $a ;# -> a b c1 2 3
Traverse the list
#!/usr/bin/tclsh
set days [list Monday Tuesday Wednesday Thursday \
Friday Saturday Sunday]
set n [llength $days]

23
SCRIPTING LANGUAGES LAB

set i 0
while {$i < $n} {
puts [lindex $days $i]
incr i
}
OUTPUT:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
(iv)Concatenate the list
% string is list -strict " a b {c "
0
% string is list -strict d
1
% string is list -strict " e} f"
0
% string is list -strict [concat " a b {c " d " e} f"]
1
OUTPUT:
set b 127
set c $a$b

24
SCRIPTING LANGUAGES LAB

15. Write a TCL script to comparing the file modified times.


Aim: To write a TCL script to comparing the file modified times.

Description:

Program:
proc newer { file1 file2 } {

if ![file exists $file2] {

return 1

} else {

# Assume file1 exists

expr [file mtime $file1] > [file mtime $file2]

Output:
1
File exists

25
SCRIPTING LANGUAGES LAB

16. Write a TCL script to Copy a file and translate to native format.
Aim: To write a TCL script to Copy a file and translate to native format.

Description:

Program:
proc newer { file1 file2 } {
if ![file exists $file2] {
return 1
} else {
# Assume file1 exists
expr [file mtime $file1] > [file mtime $file2]
}
}
Output:
F1 to F2

26
SCRIPTING LANGUAGES LAB

17. a) Write a Perl script to find the largest number among three
numbers.
Aim: To write a Perl script to find the largest number among three numbers.

Description:

Program:
Vi great.pl
#!/usr/bin/perl
print "Enter first number\n";
chomp($a=<stdin>);
print "Enter second number\n";
chomp($b=<stdin>);
print "Enter third number\n";
chomp($c=<stdin>);
$big=0;
if(($a > $b) && ($a > $c))
{
$big = $a;
print "The biggest number is $big \n";
}
elsif(($b > $a) && ($b > $c))
{
$big = $b;
print "The biggest number is $big \n";
}
elsif(($c > $a) && ($c > $b))
{
$big = $c;
print "The biggest number is $big \n";
}

27
SCRIPTING LANGUAGES LAB

Output:
Perl great.pl
Enter first number
4
Enter second number
2
Enter third number
5
The biggest number is 5
b) Write a Perl script to print the multiplication tables from 1-10 using
subroutines.
Aim: To write a Perl script to print the multiplication tables from 1-10 using
subroutines.
Program:
use strict;
use warnings;
use diagnostics;
use 5.01000;
&table(2,3,4);
sub table{
my $i = 1;
my $loop;
foreach $loop(@_){
for($i;$i<=10;$i++){
my $ans = $i*$loop;
print"$ans ";
}
print"\n";
}
}
@array=(1..10);
$count=1;

28
SCRIPTING LANGUAGES LAB

while($count<11)
{
foreach $mul (@array)
{
$multiply=$count*$mul;
push(@multifinal,$multiply);
}
print"@multifinal\n";
@multifinal =() ;
$count++;
}
Output:
loop 2
2 4 6 8 10 12 14 16 18 20
loop 3
loop 4

(OR)
#!/usr/local/bin/perl
use strict;
use warnings;
use diagnostics;
use 5.01000;

table( 2, 3, 4 );

sub table {
foreach my $loop (@_)
{
print $_*$loop, ' ' for 1 .. 10;
print "\n";
}

29
SCRIPTING LANGUAGES LAB

(OR)

for($i=1;$i<=12;$i++)
{
$a[$i]=$i;

for($i=1;$i<=12;$i++)
{
for($j=1;$j<=12;$j++)
{
print(($a[$j]*$a[$i])," ");
}
print "\n\n";
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144

30
SCRIPTING LANGUAGES LAB

18. Write a Perl program to implement the following list of


manipulating functions
a) Shift
b) Unshift
c) Push

Aim: To write a Perl program to implement the following list of manipulating


functions
a) Shift
b) Unshift
c) Push.
Description:
Perl provides various inbuilt functions to add and remove the elements in an
array.

Function Description

push Inserts values of the list at the end of an array

pop Removes the last value of an array

shift Shifts all the values of an array on its left

unshift Adds the list element to the front of an array

a)push function

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)

31
SCRIPTING LANGUAGES LAB

Program:

#!/usr/bin/perl

# 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
b) pop function

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)

32
SCRIPTING LANGUAGES LAB

Program:
#!/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

c) shift function
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)

33
SCRIPTING LANGUAGES LAB

Program:

#!/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++
d) unshift function
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)

34
SCRIPTING LANGUAGES LAB

Program:
#!/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');
# 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++

35
SCRIPTING LANGUAGES LAB

19. a) Write a Perl script to substitute a word, with another word in a


string.

Aim: To write a Perl script to substitute a word, with another word in a


string.
Description:

Program:
Substitution Operator or ‘s’ operator in Perl is used to substitute a text of
the string with some pattern specified by the user.

Syntax: s/text/pattern

Returns: 0 on failure and number of substitutions on success

Program1:
#!/usr/bin/perl -w

# String in which text


# is to be replaced
$string = "GeeksforGeeks";

# Use of s operator to replace


# text with pattern
$string =~ s/for/to/;

# Printing the updated string


print "$string\n";
Output:
GeekstoGeeks
Program2:
#!/usr/bin/perl -w

36
SCRIPTING LANGUAGES LAB

# String in which text


# is to be replaced
$string = "Hello all!!! Welcome here";

# Use of s operator to replace


# text with pattern
$string =~ s/here/to Geeks/;
# Printing the updated string
print "$string\n";
Output:
Hello all!!! Welcome to Geeks
b) Write a Perl script to validate IP address and email address.

Aim: To write a Perl script to validate IP address and email address.

Description:
Perl stands for Practical Extraction and Reporting Language and this
not authorized acronym. One of the most powerful features of the Perl
programming language is Regular Expression and in this article, you will
learn how to extract an IP address from a string. A regular expression can
be either simple or complex, depending on the pattern you want to match
like our title – Extracting IP Address from a String using Regex. Extracting
IP address from a string can be a simple or challenging task. Hence, people
love and hate regular expressions. They are a great way to express a simple
pattern and a horrific way to express complicated ones. Some of the
examples of Quantifiers as well as Characters and their meaning is given
below:

37
SCRIPTING LANGUAGES LAB

Quantifier Meaning

a* zero or more a’s

a+ one or more a’s

a? zero or one a’s

a{m} exactly m a’s

a{m,} at least m a’s

a{m,n} at least m but at most n a’s

Character Meaning

^ beginning of string

$ end of string

. any character except newline

* match 0 or more times

+ match 1 or more times

? match 0 or 1 times

| alternative

38
SCRIPTING LANGUAGES LAB

() grouping

[] set of characters

{} repetition modifier

\ quote or special

Extracting an IP Address from a String


The easiest way is just to take any string of four decimal numbers separated
by periods is

\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ OR /^\d+\.\d+\.\d+\.\d+$/

In the following example we simply extracting an IP address from a given


string.
Program:
#!/usr/bin/perl

my $ip = "MY IP ADDRESS IS172.26.39.41THIS IS A VALID IP ADDRESS";

if($ip =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/)
{
$ip = $1;
print "$ip\n";
}

39
SCRIPTING LANGUAGES LAB

Output:

But, the above example also accepts the wrong IP address like
596.368.258.269. We know, a proper decimal dotted IP address has no
value larger than 255 and writing a regex that matches the integers 0 to 255
is hard work as the regular expressions don’t understand arithmetic; they
operate purely textually. Therefore, you have to describe the integers 0
through 255 in purely textual means.
Program:
#!/usr/bin/perl

my $ip = "MY IP ADDRESS IS 36.59.63 THIS IS A VALID IP


ADDRESS";

if($ip =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/)
{
if($1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255)
{
print("Each octet of an IP address ",
"is within the range - $1\n");
print("\nIP address accepted!\n");
}
else
{
print("Octet not in range - $1\n",
"IP address not accepted\n");
}
}

40
SCRIPTING LANGUAGES LAB

else
{
print("Valid IP address not found in a given string\n");
}
Output:

If you change the string to

[my $ip = "MY IP ADDRESS IS 127.36.59.63 THIS IS A VALID IP


ADDRESS";]
then the output is

In the following example, we are accepting a string from the user which
contains an IP address and then we are extracting the IP address from it. We
used the chomp() function to remove any newline character from the end of
a string.

41
SCRIPTING LANGUAGES LAB

Program:
#!/usr/bin/perl

print("Enter the IP Address you would like to validate - ");


my $ip = <STDIN>;

if($ip =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/)
{
$ip = $1;
}

chomp($ip);

if($ip =~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/)
{
print("\nIP address found - $ip\n");
if($1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255)
{
print("Each octet of an IP address is ",
"within the range - $1.$2.$3.$4\n");
print("\n-> $ip IP address accepted!\n");
}
else
{
print("Octet(s) out of range. ",
"Valid number range between 0-255\n");
}
}
else
{
print("IP Address $ip is not in a valid format\n");
}

42
SCRIPTING LANGUAGES LAB

Output:

43
SCRIPTING LANGUAGES LAB

20. Write a Perl script to print the file in reverse order using command
line arguments.

Aim: To write a Perl script to print the file in reverse order using command
line arguments.

Program:
My Perl reverse array example

Here's the source code for my Perl "reverse file contents" program:

#!/usr/bin/perl

# rcat - a program to display the contents of a file in reverse order.

# author - alvin alexander, devdaily.com.

@lines = <>;

print reverse @lines;

Output:

To run this Perl script from the Unix/Linux command line, first save it in a
file named rcat, and then make it executable, like this:

chmod +x rcat

After that, assuming you have a file named numbers that has contents like
this:

1 2 3 4 5

if you run this command:

rcat numbers

you will see this output:


5 4 3 2 1

44

You might also like