0% found this document useful (0 votes)
50 views98 pages

Unit 3: Introduction To PERL and Scripting

This document introduces Perl and scripting, explaining the differences between scripts and programs, their execution methods, and use cases. It covers the evolution of scripting languages, their characteristics, and various applications, including web scripting and automation. Additionally, it provides examples of Perl scripts and control structures, emphasizing Perl's role in text processing and system administration.

Uploaded by

2203a51329
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)
50 views98 pages

Unit 3: Introduction To PERL and Scripting

This document introduces Perl and scripting, explaining the differences between scripts and programs, their execution methods, and use cases. It covers the evolution of scripting languages, their characteristics, and various applications, including web scripting and automation. Additionally, it provides examples of Perl scripts and control structures, emphasizing Perl's role in text processing and system administration.

Uploaded by

2203a51329
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/ 98

UNIT 3

Introduction to PERL and Scripting


This section introduces the world of scripting languages, the concept of
scripts vs. programs, and sets the foundation for understanding Perl as a
powerful scripting language.

Scripts and Programs


Definition
Term Description
A short program written in a scripting language, typically
Script
interpreted.
A compiled set of instructions that can be executed by the
Program
machine directly.

Example:
Script (Perl)
#!/usr/bin/perl
print "Hello, Script World!\n";
• Saved as: hello.pl
• Run using: perl hello.pl
Program (C)
#include <stdio.h>
int main() {
printf("Hello, Program World!\n");
return 0;
}
• Compiled: gcc hello.c -o hello
• Run: ./hello

Key Differences
Feature Script Program
Execution Interpreted (line-by-line) Compiled (whole file)
Slower (due to
Speed Faster
interpretation)
Full applications, system
Use Case Automation, small tasks
software
Feature Script Program
Development
Shorter Longer
Time
Flexibility Highly flexible Rigid, needs compilation
Error Handling Run-time Compile-time
Perl, Python, Bash,
Examples C, C++, Java
JavaScript

Execution Flow Diagram


📍 Scripts (Interpreted)
+---------------------+ +---------------------+
| Script Source Code | -----> | Interpreter (Perl) | -----> Output
+---------------------+ +---------------------+
📍 Programs (Compiled)
+----------------------+ +--------------------+ +-----------+
| Program Source Code | --> | Compiler (e.g. GCC)| --> | Executable|
+----------------------+ +--------------------+ +-----------+

Executed

Why Use Scripts?


Scripts are used when:
• Tasks are repetitive (e.g., log rotation)
• Rapid prototyping is needed
• Portability across OS is desired
• Working with text, files, or automation

Where Scripts and Programs Interact


Often, scripts call programs. For example:
Shell Script calling a compiled binary:
#!/bin/bash
echo "Starting backup..."
./backup_app # compiled C program
echo "Backup complete."

Real-Life Examples
Use Case Script Used Description
System Admin Task Bash, Perl Create users, manage files
Use Case Script Used Description
Web Form Data
Perl, PHP Process user input
Handling
Python, Shell
Automated Testing Run tests on software builds
Scripts
Data Extraction from Use regex to extract useful
Perl, Python
Logs information

Brief Mention of Perl in Context


Perl stands for:
Practical Extraction and Report Language
• Originally developed for report generation and text manipulation.
• Perl scripts are used extensively in bioinformatics, system
administration, and web CGI scripting.
Example Perl Script: Automating a Text Search
#!/usr/bin/perl
use strict;
use warnings;

open(my $fh, '<', 'file.txt') or die "Can't open file!";


while (<$fh>) {
print if /error/i; # Print lines with 'error', case-insensitive
}
close($fh);

Summary
Concept Key Point
Script Interpreted, quick, dynamic
Program Compiled, structured, efficient
Scripting Uses Automation, web, system tasks
Perl’s Role Versatile scripting for text, web, admin

Scripting Fundamentals
Covers:
• Origin of Scripting
• Scripting Today
• Characteristics of Scripting Languages
• Uses for Scripting Languages
• Web Scripting
• The Universe of Scripting Languages

1. Origin of Scripting
Background
• Originated in the early days of UNIX with Shell scripts (e.g., sh,
bash) to automate OS-level tasks.
• Grew out of a need to control software environments without
compiling full programs.
Evolution Path:
Manual Tasks

Batch files (DOS, Unix .sh)

Shell Scripting (sh, bash)

Advanced Text Processing (AWK, sed)

PERL – 1987 (Larry Wall)

Modern Scripting (Python, JavaScript, PHP)

Key Milestones:
• 1970s – Unix Shell scripting (Bourne Shell)
• 1980s – AWK, sed for text processing
• 1987 – Perl: Bridged system programming and text processing
• 1990s – Rise of web scripting (JavaScript, PHP)
• 2000s – Python, Ruby become popular for multi-domain scripting

2. Scripting Today
Current Role of Scripting:
• Scripting is now ubiquitous, used in:
o Web development
o System automation
o Machine learning
o Cloud DevOps
o Cybersecurity
o Data science
Modern Tools:
• Python: Data, ML, automation
• JavaScript: Web frontend
• Bash/PowerShell: Sysadmin
• Lua: Game engines (Roblox, WoW)
• Perl: Legacy systems, text parsing
How it's used today:
User clicks a button on a website →
JavaScript (Client-side) runs →
Sends request to server →
Python/PHP/Perl handles request (Server-side) →
Fetches from database →
Returns result

3. Characteristics of Scripting Languages


Key Traits:
Characteristic Description
Not compiled; executed line-by-line by
Interpreted
interpreter
Dynamic Typing No need to declare variable types
Rapid Development Easy to write, modify, and test
String Handling Built-in string processing and regex
Fewer rules compared to compiled
Loosely Structured
languages
Can glue other programs (called “glue
Easy Integration
code”)
Automatic Memory
No manual memory allocation required
Management
Mostly cross-platform if interpreter is
Platform Independence
installed

Example (Dynamic typing in Perl):


my $var = "hello"; # string
$var = 42; # now it's an integer

4. Uses for Scripting Languages


Common Applications:
Area Scripting Use Language
System
Automating backups, updates Bash, Perl
Administration
Area Scripting Use Language
Web Development Frontend interactivity JavaScript
PHP, Python,
Server-side logic
Perl
Data Analysis Processing large datasets Python, R
AI & ML Training models Python
Auto report generation, file
Automation Shell, Python
handling
Network Scripting Pinging, scanning, automation Python, Perl
Game Scripting Character control, physics Lua, Python

Real-World Example: Auto Email Report


#!/usr/bin/perl
use strict;
use warnings;
use MIME::Lite;

my $msg = MIME::Lite->new(
From => '[email protected]',
To => '[email protected]',
Subject => 'Automated Report',
Data => 'Attached is your report...'
);

$msg->send;

5. Web Scripting
Definition:
Scripts used to create dynamic web pages and client-server interaction.

Types:
Type Language Description
Client-side JavaScript Runs in browser, interactive UI
Server-side PHP, Perl, Python Processes requests, accesses DB

⚙️ Web Scripting Flowchart:


User Request (Browser)

Client-side JavaScript validates input

Server-side script (Perl/PHP) processes data

Database is accessed (if needed)

Response returned (HTML/JSON)

Displayed in browser

Perl Example – CGI Script


#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<html><body><h1>Hello from Perl CGI!</h1></body></html>";
Save as: hello.cgi, Run on a web server with Perl CGI enabled.

6. Universe of Scripting Languages


Categories and Usage
Language Domain Key Feature
Perl Text processing, sysadmin, web Regular expressions
Readable syntax, huge
Python AI, ML, automation, web
libraries
JavaScript Web frontend, UI interaction DOM manipulation
Easy integration with
PHP Server-side scripting
HTML
Bash Unix shell scripting Command line automation
PowerShell Windows scripting System management tools
Ruby Web development Elegant, expressive syntax
Game scripting, embedded
Lua Lightweight, fast
systems
R Statistical computing Data visualization

Comparison Diagram:
+-----------------------------+
| Scripting Use |
+-----------------------------+
| Web UI → JavaScript |
| Web Backend → PHP, Perl |
| Automation → Python, Bash |
| AI/ML → Python, R |
| Game Dev → Lua, Python |
| Sysadmin → Perl, Bash |
+-----------------------------+

Summary Table
Topic Key Takeaway
From shell scripts to powerful tools like Perl
Origin
and Python
Scripting Today Used everywhere – from websites to AI
Characteristics Interpreted, dynamic, fast for development
Uses Web, automation, system admin, data science
Web Scripting Handles user interaction and backend logic
Scripting Language Wide range of tools tailored to different
Universe domains

WEB SCRIPTING

Certainly! Here's a detailed example of Web Scripting using Perl (CGI) for the
server-side and HTML + JavaScript for the client-side.

Web Scripting Example


Goal: Create a web page that accepts a name and returns a greeting using a Perl
script on the server.

Client Side (HTML + JavaScript)


<!DOCTYPE html>
<html>
<head>
<title>Greeting Form</title>
<script>
function validateForm() {
var name = document.forms["greetForm"]["username"].value;
if (name == "") {
alert("Name must be filled out!");
return false;
}
return true;
}
</script>
</head>
<body>
<h2>Welcome!</h2>
<form name="greetForm" action="/cgi-bin/greet.pl" method="GET"
onsubmit="return validateForm();">
Enter your name: <input type="text" name="username">
<input type="submit" value="Greet Me">
</form>
</body>
</html>
What it does:
• HTML provides the form.
• JavaScript checks that the name field is not empty before submitting the
form.

Server Side (Perl CGI Script)


Save the following script as greet.pl in the server’s cgi-bin folder:
#!/usr/bin/perl

use strict;
use warnings;
use CGI;

my $cgi = CGI->new;
print $cgi->header('text/html');

my $name = $cgi->param('username') || "Guest";

print "<html><body>";
print "<h1>Hello, $name!</h1>";
print "</body></html>";
What it does:
• Retrieves the username parameter from the form.
• Prints a personalized greeting in an HTML response.

Flow Diagram
[User opens HTML form]

[Fills in name and submits]

[Client-side JS validates input]

[Form submitted to server: /cgi-bin/greet.pl?username=Alice]

[Perl script processes data]

[Server returns: "Hello, Alice!"]

How to Run:
1. You need a web server like Apache with CGI enabled.
2. Place HTML in htdocs/ and Perl script in cgi-bin/.
3. Make Perl script executable:
4. chmod +x greet.pl

✅ Output Example
When a user enters Alice and submits, the server responds with:
<h1>Hello, Alice!</h1>

Certainly! Let's dive deep into the concept of Names and Values and
Variables in Perl — with definitions, rules, syntax, examples, and
outputs.

1. Names and Values in Perl


What are "Names"?
• Names are identifiers used to refer to variables in Perl.
• They are the symbolic representation of memory locations that hold
values.
What are "Values"?
• Values are the actual data stored in variables (like numbers, strings,
references, etc.).
• A name points to a value, but the same value can be shared or changed
independently of its name.
Example:
my $x = 10;
my $y = $x;
$y = 20;

print "x: $x\n"; # Still 10


print "y: $y\n"; # Changed to 20
Interpretation:
• $x and $y were pointing to the same value (10) at first.
• Changing $y to 20 does not affect $x because now $y points to a new
value.
Naming Rules in Perl
Rule Example
Names start with a sigil ($, @, %) $var, @list
Must begin with a letter or underscore $name, $_id
Can contain letters, digits, underscores $user_1
Case-sensitive $Name ≠ $name

2. Variables in Perl
Types of Variables:
Type Sigil Description
Scalar $ Holds a single value (number/string)
Array @ Holds an ordered list of scalars
Hash % Holds key-value pairs

Scalar Variables
Syntax:
my $name = "Alice";
my $age = 22;
my $sum = $age + 8;
print "$name is $sum years old.\n";
Output:
Alice is 30 years old.

Array Variables
Syntax:
my @colors = ("red", "blue", "green");
print $colors[1]; # blue
Output:
blue

Hash Variables
Syntax:
my %fruit_colors = ("apple" => "red", "banana" => "yellow");
print $fruit_colors{"banana"};
Output:
yellow

Example Program: Demonstrating Names and Variables


#!/usr/bin/perl
use strict;
use warnings;
my $first = 5;
my $second = $first;
$second = 10;

print "First: $first\n";


print "Second: $second\n";
Output:
First: 5
Second: 10

🔄 Summary Chart
Feature Type Example Syntax Notes
Scalar Single $x = "Hello" Stores string or number
Array List @a = (1,2,3) Indexed from 0
Hash Mapping %h = ("a"=>1) Access via keys
Name Label $name Refers to a memory location
Value Data "Hello", 123 Can be copied/shared

Control Structures in Perl


Control Structures in Perl
Control structures are used to control the flow of execution in a Perl program,
based on conditions or repetition.

Categories of Control Structures


Category Keywords Purpose
Conditional if, elsif, else, unless Decision-making
Looping while, until, for, foreach Repetition
Loop Control next, last, redo Control loop behavior

1. Conditional Structures
a) if, elsif, else
Syntax:
if (condition) {
# code block
} elsif (another_condition) {
# another block
} else {
# fallback block
}
Example:
my $age = 20;

if ($age >= 18) {


print "You can vote\n";
} else {
print "Too young to vote\n";
}
Output:
You can vote

b) unless (opposite of if)


Syntax:
unless (condition) {
# code runs if condition is false
}
Example:
my $x = 5;
unless ($x > 10) {
print "x is NOT greater than 10\n";
}
Output:
x is NOT greater than 10

2. Looping Structures

a) while
Executes a block as long as the condition is true.
Example:
my $i = 0;
while ($i < 3) {
print "i = $i\n";
$i++;
}
Output:
i=0
i=1
i=2

b) until
Opposite of while — runs until the condition becomes true.
Example:
my $j = 0;
until ($j > 2) {
print "j = $j\n";
$j++;
}
Output:
j=0
j=1
j=2

c) for loop (C-style)


Syntax:
for (initialization; condition; increment) {
# loop body
}
Example:
for (my $k = 0; $k < 3; $k++) {
print "k = $k\n";
}
Output:
k=0
k=1
k=2

d) foreach loop
Used to iterate through an array/list.
Example:
my @fruits = ("apple", "banana", "cherry");

foreach my $fruit (@fruits) {


print "$fruit\n";
}
Output:
apple
banana
cherry

3. Loop Control Keywords


a) next → Skip to next iteration
for my $i (1..5) {
next if $i == 3;
print "$i\n";
}
Output:
1
2
4
5

b) last → Exit the loop


for my $i (1..5) {
last if $i == 3;
print "$i\n";
}
Output:
1
2

c) redo → Restart current iteration without re-evaluating condition


my $count = 0;
while ($count < 3) {
print "Count: $count\n";
$count++;
redo if $count == 2;
}
Output:
Count: 0
Count: 1
Count: 1
Count: 2

Control Flow Diagram: if-elsif-else


+------------------+
| condition? |
+------------------+
|
+---------+--------+
| |
True False
| |
+----------------+ +-------------+
| execute if block| | check elsif |
+----------------+ +-------------+

Full Example Program:


#!/usr/bin/perl
use strict;
use warnings;

my @nums = (1..5);

foreach my $n (@nums) {
if ($n % 2 == 0) {
print "$n is even\n";
} else {
print "$n is odd\n";
}
}
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd

Summary Table
Structure Usage
if, else Condition-based branching
unless Run block if condition is false
while Repeat while condition is true
until Repeat until condition becomes true
for Loop with initialization, condition, step
foreach Iterate over lists/arrays
next Skip to next iteration
last Break out of loop
redo Restart current iteration

ARRAYS
Absolutely! Here's a complete Perl program that demonstrates multiple array
operations including:
• Creation
• Insertion (push, unshift)
• Deletion (pop, shift)
• Traversal
• Sorting
• Searching
• Joining and slicing
Perl Array Program with Multiple Operations
#!/usr/bin/perl
use strict;
use warnings;

# Declare and initialize array


my @fruits = ("apple", "banana", "cherry");

print "Original array: @fruits\n";

# Add elements
push(@fruits, "mango"); # Add to end
unshift(@fruits, "grape"); # Add to beginning

print "After push and unshift: @fruits\n";

# Remove elements
my $last = pop(@fruits); # Remove last
my $first = shift(@fruits); # Remove first

print "After pop and shift: @fruits\n";


print "Removed first: $first, last: $last\n";

# Array length
my $len = scalar @fruits;
print "Length of array: $len\n";

# Loop through array


print "Traversing array:\n";
foreach my $item (@fruits) {
print "- $item\n";
}

# Sort array
my @sorted = sort @fruits;
print "Sorted array: @sorted\n";

# Join array elements to string


my $joined = join(", ", @fruits);
print "Joined string: $joined\n";

# Slice array
my @slice = @fruits[0, 1];
print "Sliced array (first two): @slice\n";

# Search for an element


my $search = "banana";
my $found = 0;
foreach my $f (@fruits) {
if ($f eq $search) {
$found = 1;
last;
}
}
print $found ? "$search found in array\n" : "$search not found\n";

Expected Output
Original array: apple banana cherry
After push and unshift: grape apple banana cherry mango
After pop and shift: apple banana cherry
Removed first: grape, last: mango
Length of array: 3
Traversing array:
- apple
- banana
- cherry
Sorted array: apple banana cherry
Joined string: apple, banana, cherry
Sliced array (first two): apple banana
banana found in array

🔍 Explanation of Key Operations


Operation What It Does
push Adds element to end of array
unshift Adds element to beginning
pop Removes last element
shift Removes first element
scalar @array Gives total number of elements
foreach Loops through array
sort Alphabetically sorts array
join Converts array to string with separator
@array[x,y] Slices part of array
Arrays and Lists in Perl
In Perl, arrays and lists are used to store ordered collections of scalar values
(strings, numbers, etc.).

✅ What is an Array?
• An array is a variable that holds an ordered list of scalar values.
• The array name starts with @, and individual elements are accessed using
$ with index.

Declaring an Array
my @colors = ("red", "green", "blue");

What is a List?
• A list is a fixed sequence of values.
• It can be assigned to an array, passed to functions, or returned from
subroutines.
• Lists are usually written inside parentheses ().
💡 Example:
(1, 2, 3, 4); # This is a list

my @nums = (1, 2, 3); # List assigned to array

What is a List in Perl?

In Perl, a list is an ordered collection of scalar values. It is very similar to an


array but is often used:
• As a value (e.g., to initialize an array or pass arguments)
• In function return statements
• As inline values
A list is written inside parentheses (), and doesn’t have a name unless it is
assigned to an array.

Declaring and Using Lists


perl
CopyEdit
my @nums = (1, 2, 3, 4); # List assigned to an array
You cannot manipulate a list directly (like pop/push), but once assigned to an
array, you can.

Common Use Cases of Lists


Use Case Example
Assignment to array @arr = (10, 20, 30);
Returning multiple values return (1, 2, 3);
Passing multiple arguments print_list("one", "two", "three");
Inline list usage my $sum = 10 + (1, 2, 3); (returns 3)

Note
When used in scalar context, the list returns the last element of the list:
perl
CopyEdit
my $x = (10, 20, 30); # $x = 30

Accessing Array Elements


my @fruits = ("apple", "banana", "cherry");

print $fruits[0]; # apple


print $fruits[2]; # cherry
Indexing starts from 0 in Perl.

Common Array Operations


Operation Syntax / Example Description
Length scalar @array Get size of array
Add (end) push @array, $val Add element at the end
Remove (end) pop @array Remove last element
Add (beginning) unshift @array, $val Add at beginning
Remove (beginning) shift @array Remove from beginning
Slice @slice = @array[0,2] Get multiple values
Join join(",", @array) Join array to string
Sort @sorted = sort @array Sort elements
Reverse @reversed = reverse @array Reverse elements

Example 1: Basic Array Operations


#!/usr/bin/perl
use strict;
use warnings;

my @nums = (10, 20, 30);

push @nums, 40; # Add at end


unshift @nums, 5; # Add at beginning
pop @nums; # Remove last
shift @nums; # Remove first

print "Array: @nums\n";


print "Length: ", scalar @nums, "\n";
Output:
Array: 10 20 30
Length: 3

Iterating through Arrays


Using foreach
my @names = ("Alice", "Bob", "Charlie");

foreach my $name (@names) {


print "$name\n";
}
Output:
Alice
Bob
Charlie

Example 2: Array Slicing, Sorting, Joining


my @langs = ("Perl", "Python", "C", "Java");
my @slice = @langs[1,3];

print "Sliced: @slice\n";

my @sorted = sort @langs;


print "Sorted: @sorted\n";

my $joined = join(" - ", @langs);


print "Joined: $joined\n";
Output:
Sliced: Python Java
Sorted: C Java Perl Python
Joined: Perl - Python - C - Java

List Context vs Scalar Context


Perl expressions behave differently based on context — list vs scalar.
my @a = (1, 2, 3);
my $count = @a; # scalar context → returns number of elements
print "Count: $count\n"; # 3

Numeric Arrays vs String Arrays


my @nums = (1, 2, 3, 4);
my @words = ("apple", "ball", "cat");

print $nums[2]; # 3
print $words[0]; # apple

Summary Chart
Feature Array Example List Example
Declaration @arr = (1,2,3) (1,2,3)
Access $arr[1] → 2 N/A
Length scalar @arr N/A
Looping foreach my $i (@arr) Used inline or as return
Use Case Dynamic collection Fixed sequence of values

Visual Summary
Array @nums: [10] [20] [30] [40]
Access element: $nums[2] → 30
List assigned: (1, 2, 3) → @arr

Hashes in Perl
In Perl, a hash is an unordered set of key-value pairs, similar to dictionaries in
Python or objects in JavaScript. They are extremely useful for storing and
retrieving data quickly by key.

Basic Syntax of Hashes


my %hash = (
"apple" => "red",
"banana" => "yellow",
"grape" => "purple"
);
• % denotes a hash.
• Keys are strings.
• Values can be strings, numbers, arrays, etc.

Accessing Hash Elements


print $hash{"apple"}; # Output: red
Use curly braces {} and a $ prefix to get a value.

Adding or Modifying Elements


$hash{"orange"} = "orange"; # Add new key-value
$hash{"banana"} = "green"; # Modify value

Deleting Elements
delete $hash{"grape"};

Looping Through Hashes


Example 1: each loop
while (my ($key, $value) = each %hash) {
print "$key is $value\n";
}
Example 2: keys and values
foreach my $fruit (keys %hash) {
print "$fruit color is $hash{$fruit}\n";
}

Full Example Program with Output


#!/usr/bin/perl
use strict;
use warnings;

my %colors = (
"apple" => "red",
"banana" => "yellow",
"grape" => "purple"
);

# Add a new key-value pair


$colors{"orange"} = "orange";

# Modify an existing value


$colors{"banana"} = "green";

# Delete a key
delete $colors{"grape"};

# Print all key-value pairs


foreach my $fruit (keys %colors) {
print "$fruit is $colors{$fruit}\n";
}
Output:
orange is orange
banana is green
apple is red
(Note: Hashes are unordered, so output order may vary.)

Useful Hash Functions


Function Purpose
keys %hash Returns all keys
values %hash Returns all values
exists $hash{key} Checks if key exists
delete $hash{key} Removes key-value pair

Example: Checking Existence of Key


if (exists $colors{"apple"}) {
print "Apple exists!\n";
}

1. Strings in Perl
What is a String?
A string is a sequence of characters stored in a scalar variable.
Declaring a String
my $greet = "Hello, World!";

String Operators
Operator Description Example
. Concatenation "Hello" . " World" = "Hello World"
x Repetition "ha" x 3 = "hahaha"

String Functions
Function Description
length($s) Returns the number of characters
index($s, "x") Finds the first occurrence of "x"
substr($s, start, len) Extract substring
lc($s) / uc($s) Lowercase / Uppercase
chomp($s) Removes trailing newline
chop($s) Removes last character

String Example Program


#!/usr/bin/perl
use strict;
use warnings;

my $str = "Hello, Perl!";


print "Original: $str\n";
print "Length: ", length($str), "\n";
print "Uppercase: ", uc($str), "\n";
print "Substring (7,4): ", substr($str, 7, 4), "\n";
Output:
Original: Hello, Perl!
Length: 12
Uppercase: HELLO, PERL!
Substring (7,4): Perl

2. Patterns and Regular Expressions in Perl

What is a Regular Expression?


A regular expression (regex) is a pattern that describes a set of strings. Perl has
built-in support using =~, !~, and other regex operators.

Basic Syntax
$string =~ /pattern/ # Match
$string !~ /pattern/ # Does NOT match
$string =~ s/old/new/ # Substitute
$string =~ tr/a-z/A-Z/ # Translate

Regex Meta-characters
Symbol Meaning Example
. Any single character a.c matches abc, acc
* 0 or more times go*gle matches ggle, google
+ 1 or more times lo+l matches lol, lool
? 0 or 1 time colou?r matches color, colour
^ Start of line ^Hi matches string starting with Hi
$ End of line end$ matches string ending with end
\d Any digit \d+ matches numbers
\w Word character \w+ matches alphanumeric words
\s Whitespace \s+ matches spaces or tabs
[...] Character class [aeiou] matches vowels

Regex Modifiers
Modifier Meaning
i Case-insensitive match
g Global match (all matches)
m Multiline mode

Example 1: Matching Pattern


my $text = "I love Perl!";
if ($text =~ /Perl/) {
print "Perl is present!\n";
}
Output:
Perl is present!

Example 2: Substitute Pattern


my $line = "apples are red";
$line =~ s/red/green/;
print "$line\n";
Output:
apples are green

Example 3: Extracting from String


my $email = "[email protected]";
if ($email =~ /(.+)@(.+)/) {
print "User: $1\nDomain: $2\n";
}
Output:
User: john.doe
Domain: example.com

tr/// - Transliteration
Changes specific characters:
my $msg = "hello";
$msg =~ tr/a-z/A-Z/; # Convert to uppercase
print "$msg\n"; # Output: HELLO

Regular Expression in Loops


my @lines = ("dog", "cat", "bat", "rat");

foreach my $item (@lines) {


if ($item =~ /^.at$/) {
print "$item matches .at\n";
}
}
Output:
cat matches .at
bat matches .at
rat matches .at

Summary Table
Feature Syntax Example Description
Match $a =~ /cat/ Check if pattern exists
Substitute $a =~ s/dog/cat/ Replace word
Extract /(\w+)@(\w+)/ Use () to extract groups
Global Match $a =~ s/a/b/g Replace all occurrences
Translate $a =~ tr/abc/xyz/ Replace characters one by one

SUBROUTINES

Subroutines in Perl

What is a Subroutine?
A subroutine (also known as a function in other languages) is a named block of
reusable code that performs a specific task. It helps modularize code, improve
readability, and allows for reuse.

Syntax
sub subroutine_name {
# Code block
}
To call a subroutine:
subroutine_name(); # or just subroutine_name;

Example 1: Basic Subroutine


#!/usr/bin/perl
use strict;
use warnings;

sub greet {
print "Hello from subroutine!\n";
}

greet(); # Call the subroutine


Output:
Hello from subroutine!

Passing Arguments to Subroutines


Arguments passed to a subroutine are stored in the special array @_.
Example 2: Subroutine with Arguments
sub add {
my ($a, $b) = @_; # @_ contains arguments
my $sum = $a + $b;
print "Sum: $sum\n";
}

add(10, 5); # Call with arguments


Output:
Sum: 15

Returning Values from Subroutines


Use the return keyword to return a value (or list) from a subroutine.
Example 3: Subroutine with Return Value
sub square {
my $n = shift; # Gets first argument
return $n * $n;
}

my $result = square(6);
print "Square: $result\n";
Output:
Square: 36

Subroutine Returning a List


sub get_stats {
my ($a, $b) = @_;
return ($a + $b, $a * $b);
}

my ($sum, $prod) = get_stats(4, 5);


print "Sum: $sum, Product: $prod\n";
Output:
Sum: 9, Product: 20

Advanced Concepts
shift Keyword
Retrieves and removes the first element from @_:
sub greet_user {
my $name = shift;
print "Hello, $name!\n";
}
Default Arguments (Manual)
Perl does not support default arguments directly, but you can simulate:
sub hello {
my $name = shift || "Guest";
print "Hi, $name!\n";
}

hello("Alice"); # Hi, Alice!


hello(); # Hi, Guest!

Example Program Using All Concepts


#!/usr/bin/perl
use strict;
use warnings;

# Subroutine to greet user


sub greet {
my $name = shift || "User";
print "Hello, $name!\n";
}

# Subroutine to calculate factorial


sub factorial {
my $n = shift;
my $fact = 1;
for (my $i = 1; $i <= $n; $i++) {
$fact *= $i;
}
return $fact;
}

# Subroutine to find max of a list


sub find_max {
my @list = @_;
my $max = $list[0];
foreach my $item (@list) {
if ($item > $max) {
$max = $item;
}
}
return $max;
}

# Calling subroutines
greet("John");
my $f = factorial(5);
print "Factorial: $f\n";

my @nums = (10, 25, 5, 40, 18);


my $max_val = find_max(@nums);
print "Maximum value: $max_val\n";
Output:
Hello, John!
Factorial: 120
Maximum value: 40

Summary Table
Feature Syntax / Concept
Declare subroutine sub name { ... }
Call subroutine name(); or name(@args);
Arguments @_, or my ($a, $b) = @_
Return value return $value;
Return multiple vals return ($x, $y);
shift usage Gets first value from @_
Default argument `$var = shift

UNIT 4
introduction to PHP, working with variables and constants, and controlling
program flow in detail

1. Introducing PHP
What is PHP?
• PHP (Hypertext Preprocessor) is a server-side scripting language
primarily used for web development.
• PHP is embedded within HTML, making it easy to integrate dynamic
content into websites.
• PHP can be used for tasks like form handling, interacting with databases,
session management, and more.
How PHP Works
When a PHP file is requested by a browser, the server processes the PHP code
and generates HTML that is sent back to the browser.

Basic Syntax of PHP


PHP code is typically embedded in HTML using the <?php ?> tags:
<?php
// This is a PHP block
echo "Hello, World!"; // Output: Hello, World!
?>
PHP File Extension: .php

2. Working with Variables and Constants


Variables in PHP
A variable in PHP is used to store data. PHP variables:
• Start with the dollar sign ($).
• Are case-sensitive.
• Do not require type declarations (dynamically typed).
Syntax for Variables
<?php
$variable_name = value;
?>
Example: Defining and Using Variables
<?php
$name = "Alice"; // String
$age = 25; // Integer
$is_student = true; // Boolean

echo "Name: $name, Age: $age, Is Student: $is_student";


?>
Constants in PHP
Constants are values that cannot be changed after being defined.
• Constants are defined using the define() function or const keyword.
• Constants are globally available throughout the script.
Syntax for Constants
define("CONSTANT_NAME", "value"); // Using define()
const CONSTANT_NAME = "value"; // Using const
Example: Defining and Using Constants
<?php
define("SITE_NAME", "MyWebsite");

echo "Welcome to " . SITE_NAME; // Output: Welcome to MyWebsite


?>

3. Controlling Program Flow


Controlling the flow of a PHP program involves using conditional statements,
loops, and other control structures.

Conditional Statements
Conditional statements execute a block of code based on whether a condition is
true or false.
📌 if, else, elseif
<?php
$age = 18;

if ($age < 18) {


echo "You are a minor.";
} elseif ($age == 18) {
echo "You just turned 18!";
} else {
echo "You are an adult.";
}
?>
Output:
You are an adult.
📌 switch Statement
The switch statement is used to evaluate multiple conditions based on a single
variable.
<?php
$day = "Monday";

switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Almost weekend!";
break;
default:
echo "Midweek!";
}
?>
Output:
Start of the week!

Loops
PHP provides several types of loops to repeat a block of code.
for Loop
The for loop runs a block of code a specific number of times.
<?php
for ($i = 0; $i < 5; $i++) {
echo "Iteration: $i<br>";
}
?>
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
while Loop
The while loop runs as long as the condition evaluates to true.
<?php
$i = 0;
while ($i < 5) {
echo "Iteration: $i<br>";
$i++;
}
?>
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
foreach Loop
The foreach loop is used to iterate over arrays.
<?php
$colors = array("Red", "Green", "Blue");

foreach ($colors as $color) {


echo $color . "<br>";
}
?>
Output:
Red
Green
Blue

Summary
• Variables are used to store data, and constants store unchangeable values.
• Conditional statements (if, else, switch) allow your code to make
decisions.
• Loops (for, while, foreach) are used to execute code multiple times.

---------------------------------------------------------------------------
Working with Functions, Arrays, and Files and Directories in PHP

1. Working with Functions


What is a Function in PHP?
A function is a block of reusable code that performs a specific task. Functions
can take input (parameters) and can return a value.
Defining a Function
function function_name($parameter1, $parameter2) {
// Code block
return $result;
}
Example: Basic Function
<?php
function greet($name) {
return "Hello, $name!";
}

echo greet("Alice"); // Output: Hello, Alice!


?>
Default Parameters
You can define default values for parameters.
<?php
function greet($name = "Guest") {
return "Hello, $name!";
}

echo greet(); // Output: Hello, Guest!


echo greet("Alice"); // Output: Hello, Alice!
?>
Returning Values
Functions can return a value using the return keyword.
<?php
function sum($a, $b) {
return $a + $b;
}

echo sum(5, 10); // Output: 15


?>
Variable Scope
PHP has local and global variable scopes. Variables defined inside a function
are local, while global variables can be accessed outside functions.
$global_var = "I am global";

function test_scope() {
global $global_var; // Access global variable
echo $global_var; // Output: I am global
}

test_scope();

2. Arrays
What is an Array?
An array is a data structure that stores multiple values under a single variable.
There are two types of arrays in PHP:
1. Indexed arrays: Arrays with numeric keys.
2. Associative arrays: Arrays with named keys.

Indexed Array
An indexed array stores values with numeric indices (starting from 0 by
default).
<?php
$fruits = array("Apple", "Banana", "Orange");
echo $fruits[1]; // Output: Banana
?>
Associative Array
An associative array uses named keys to store values.
<?php
$person = array("name" => "Alice", "age" => 25, "city" => "New York");
echo $person["name"]; // Output: Alice
?>
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
<?php
$students = array(
"John" => array("age" => 20, "grade" => "A"),
"Alice" => array("age" => 22, "grade" => "B")
);
echo $students["John"]["grade"]; // Output: A
?>
Common Array Functions
• count($array) – Returns the number of elements in the array.
• array_push($array, $value) – Adds a new element at the end.
• array_pop($array) – Removes the last element.
• array_merge($array1, $array2) – Merges two arrays.
• in_array($value, $array) – Checks if a value exists in the array.

Example: Array Operations


<?php
$colors = array("Red", "Green", "Blue");
array_push($colors, "Yellow"); // Add Yellow to the end
array_pop($colors); // Remove the last element (Yellow)

foreach ($colors as $color) {


echo $color . "<br>";
}
?>
Output:
Red
Green
Blue

3. Files and Directories


Working with Files
PHP provides a set of functions for file handling — opening, reading, writing,
and closing files.

Opening a File
<?php
$file = fopen("example.txt", "w"); // Open file for writing (create if doesn't
exist)
if ($file) {
echo "File opened successfully.";
}
?>
Writing to a File
<?php
$file = fopen("example.txt", "w");
if ($file) {
fwrite($file, "Hello, this is a test file.");
fclose($file); // Close the file
}
?>
Reading from a File
<?php
$file = fopen("example.txt", "r");
if ($file) {
$content = fread($file, filesize("example.txt"));
echo $content;
fclose($file);
}
?>
Checking If File Exists
<?php
if (file_exists("example.txt")) {
echo "File exists.";
} else {
echo "File does not exist.";
}
?>

Working with Directories


Creating a Directory
<?php
mkdir("new_folder", 0777); // Create a new directory with permissions
?>
📌 Checking if a Directory Exists
<?php
if (is_dir("new_folder")) {
echo "Directory exists.";
} else {
echo "Directory does not exist.";
}
?>
Listing Files in a Directory
<?php
$files = scandir("path/to/directory"); // Get an array of files
print_r($files);
?>
Deleting a Directory
<?php
rmdir("new_folder"); // Remove the directory
?>

File Permissions
In PHP, you can set file permissions using the chmod() function.
<?php
chmod("example.txt", 0755); // Set permissions for the file
?>

Summary
1. Functions: Reusable blocks of code that accept parameters and return
values.
2. Arrays: Store multiple values under a single variable. There are indexed,
associative, and multidimensional arrays.
3. Files and Directories: PHP has built-in functions to open, read, write, and
manipulate files and directories.
---------------------------------------------------------------------------
PHP working with Forms and MySQL Databases,.

1. Working with Forms and Database in PHP


PHP Forms Overview
HTML forms are used to collect user data. PHP handles the data using $_GET
or $_POST.
Example: HTML Form
<form method="POST" action="form_handler.php">
Name: <input type="text" name="username"><br>
Email: <input type="email" name="email"><br>
<input type="submit" value="Submit">
</form>
PHP Form Handler (form_handler.php)
<?php
$name = $_POST['username'];
$email = $_POST['email'];

echo "Welcome $name! Your email is $email.";


?>

2. Database Operations Using PHP and MySQL


To interact with databases, PHP uses MySQLi or PDO. We’ll use MySQLi in
these examples.

A. Connecting to MySQL Server


<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

B. Creating a Database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

C. Selecting a Database
$conn = new mysqli($servername, $username, $password, "myDB");

D. Listing All Databases


$result = $conn->query("SHOW DATABASES");

while ($row = $result->fetch_assoc()) {


echo $row['Database'] . "<br>";
}

E. Listing All Table Names in a Database


$result = $conn->query("SHOW TABLES");

while ($row = $result->fetch_array()) {


echo $row[0] . "<br>";
}

F. Creating a Table
$sql = "CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50)
)";
if ($conn->query($sql) === TRUE) {
echo "Table created successfully";
} else {
echo "Error: " . $conn->error;
}

G. Inserting Data
$sql = "INSERT INTO users (name, email) VALUES ('Alice',
'[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully";
}
You can also collect data from a form and insert it into the database using
$_POST.

H. Selecting Data (Queries)


$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] .
" - Email: " . $row["email"] . "<br>";
}

I. Altering a Table
$sql = "ALTER TABLE users ADD age INT";
if ($conn->query($sql) === TRUE) {
echo "Table altered successfully";
}

J. Deleting Data
$sql = "DELETE FROM users WHERE name='Alice'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
}

K. Deleting a Table
$sql = "DROP TABLE users";
if ($conn->query($sql) === TRUE) {
echo "Table deleted successfully";
}
L. Deleting a Database
$sql = "DROP DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database deleted successfully";
}

3. Real-Life Workflow Summary


1. Create HTML form → Collect input.
2. Connect to MySQL using PHP.
3. Create DB and Table (if needed).
4. Insert form data into table.
5. Retrieve and display data from DB.
6. Perform CRUD (Create, Read, Update, Delete) as needed.

Example: Full Form Submission and DB Insert


HTML Form (index.html)
<form method="POST" action="insert.php">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<input type="submit" value="Register">
</form>
PHP Script (insert.php)
<?php
$conn = new mysqli("localhost", "root", "", "myDB");

$name = $_POST['name'];
$email = $_POST['email'];

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

if ($conn->query($sql) === TRUE) {


echo "User registered successfully.";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
?>

— phpMyAdmin and common database bugs in PHP.

1. phpMyAdmin
What is phpMyAdmin?
phpMyAdmin is a free and open-source web-based interface to manage MySQL
or MariaDB databases. It is often bundled with tools like XAMPP, WAMP, or
LAMP.

Key Features:
Feature Description
No need to write SQL queries manually (but you can if
GUI-based interaction
you want).
Database operations Create, delete, modify databases.
Create, modify, drop tables; set indexes, primary keys,
Table operations
etc.
Data operations Insert, update, delete, browse data visually.
Export or import databases/tables in formats like SQL,
Import/Export
CSV, Excel, PDF.
User management Manage MySQL users, set privileges, passwords.
Query console Execute custom SQL queries.
Visual relationship
Create ER diagrams (in some versions).
designer

Screenshot Preview (for understanding):


+----------------------------------------+
| phpMyAdmin |
|----------------------------------------|
| Databases | SQL | Status | Users |
+----------------------------------------+
| + Create new database |
| + Browse existing tables |
| + Run SQL queries |
+----------------------------------------+

Accessing phpMyAdmin (on localhost):


1. Start your Apache and MySQL services via XAMPP/WAMP.
2. Open browser and go to:
http://localhost/phpmyadmin
3. You’ll see the dashboard and can start working.

2. Common Database Bugs in PHP & How to Fix Them


Bug/Issue Description Fix
Wrong hostname,
Connection Double-check credentials and server
username, password, or
failed status
server down
Bug/Issue Description Fix
Using $_POST['name']
Undefined
without checking if form Use isset($_POST['name']) to verify
index
was submitted
SQL syntax Typos or missing Debug using echo $sql; and try in
errors quotes/brackets in SQL phpMyAdmin
Data not
SQL query silently fails Use $conn->error to display errors
inserted
Unsanitized user input Use mysqli_real_escape_string() or
SQL Injection
leads to vulnerability Prepared Statements
Enable error reporting:
Blank pages Errors are hidden error_reporting(E_ALL);
ini_set('display_errors', 1);
Inputs are not named
Form submits Ensure form inputs use name and
correctly or method
but no data match POST method
mismatch

Example of Debugging a Query


<?php
$conn = new mysqli("localhost", "root", "", "myDB");

$name = $_POST['name'];
$email = $_POST['email'];

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

if ($conn->query($sql) === TRUE) {


echo "Inserted!";
} else {
echo "Error: " . $conn->error; // Show the actual error
}
?>

Using phpMyAdmin for Debugging


1. Copy and paste the failing SQL into phpMyAdmin's SQL tab.
2. Run and observe syntax errors.
3. If it works in phpMyAdmin but not in PHP — it may be a code bug (like
wrong variable).

Example of Secure Insert Using Prepared Statements


$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();

Summary
• phpMyAdmin: A GUI to manage databases without needing the terminal
or coding.
• Common bugs: Mainly related to wrong connection settings, form
handling issues, SQL injection, or syntax errors.
• Best practices: Use prepared statements, always handle errors, and
sanitize inputs.

Cookies, Sessions, and PHP Security

1. Cookies in PHP
What is a Cookie?
A cookie is a small file stored on the user's browser. PHP can send cookies
using the setcookie() function.

Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Parameter Description
name Name of the cookie
value Value to be stored
expire Expiration time (in UNIX timestamp)
path Path on the server (default is "/")
secure Use HTTPS only
httponly JS cannot access (for security)

Example: Setting and Retrieving a Cookie


// Set a cookie for 1 hour
setcookie("user", "Alice", time() + 3600, "/");

if(isset($_COOKIE["user"])) {
echo "Hello, " . $_COOKIE["user"];
} else {
echo "Cookie is not set.";
}

Deleting a Cookie
setcookie("user", "", time() - 3600); // Set past expiry
2. Sessions in PHP
What is a Session?
A session stores user data on the server (unlike cookies which are stored on the
client). Session IDs are passed via cookies or URL.

Starting a Session
session_start();
Storing and Accessing Data
// Save data
$_SESSION["username"] = "Alice";

// Retrieve data
echo $_SESSION["username"];
Destroying a Session
session_start();
session_unset(); // Unset all session variables
session_destroy(); // Destroy the session

Example:
<?php
session_start();

if (!isset($_SESSION["visits"])) {
$_SESSION["visits"] = 1;
} else {
$_SESSION["visits"]++;
}
echo "Visit count: " . $_SESSION["visits"];
?>

3. PHP Security
Security is critical in web development. PHP applications must be protected
from common vulnerabilities.

A. SQL Injection
Problem: Unsanitized inputs let attackers inject SQL.
Bad Code:
$sql = "SELECT * FROM users WHERE name = '$_POST[name]'";
Fix with Prepared Statements:
$stmt = $conn->prepare("SELECT * FROM users WHERE name = ?");
$stmt->bind_param("s", $_POST['name']);
$stmt->execute();
B. Cross-Site Scripting (XSS)
Problem: Injecting scripts via input/output.
Fix:
echo htmlspecialchars($_GET["name"]);

C. Cross-Site Request Forgery (CSRF)


Problem: Unauthorized actions via tricked sessions.
Fix:
• Use CSRF tokens in forms.
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
<input type="hidden" name="csrf" value="<?php echo
$_SESSION['csrf_token']; ?>">

D. Session Hijacking
Fixes:
• Use session_regenerate_id(true); to prevent fixation.
• Use httponly and secure flags for session cookies.
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);

E. File Upload Vulnerabilities


Problem: Users upload PHP/malicious files.
Fix:
• Restrict file types (e.g., images only).
• Rename uploaded files.
• Store outside web root.
$allowed = ['jpg', 'png'];
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($ext, $allowed)) die("Invalid file type");

F. Password Handling
Never store raw passwords!
$hash = password_hash("mypassword", PASSWORD_DEFAULT);
if (password_verify("mypassword", $hash)) {
echo "Valid password!";
}

Summary
Topic Key Points
Cookies Stored in browser, use setcookie(), limited size
Sessions Stored server-side, use $_SESSION
Security Sanitize inputs, use prepared statements, CSRF tokens, and password
Topic Key Points
hashing

----------( include all the lab programs too)---------------------


food
<?php
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$database = "food_db";

$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Collect form data


$customer_name = $_POST['customer_name'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$payment = $_POST['payment'];

// Join selected food items as a string


$food_items = isset($_POST['food_items']) ? implode(", ", $_POST['food_items']) : "";

// Insert into table


$sql = "INSERT INTO food_orders (customer_name, phone, address, food_items, payment)
VALUES ('$customer_name', '$phone', '$address', '$food_items', '$payment')";

if ($conn->query($sql) === TRUE) {


echo "✅ Your food order has been placed successfully!";
} else {
echo "❌ Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
--------
<!DOCTYPE html>
<html>
<head>
<title>Food Order Form</title>
</head>
<body>
<h2>Online Food Order Form</h2>
<form action="submit_order.php" method="POST">
<label>Customer Name:</label>
<input type="text" name="customer_name" required><br><br>

<label>Phone Number:</label>
<input type="text" name="phone" required><br><br>

<label>Delivery Address:</label>
<textarea name="address" rows="4" cols="30" required></textarea><br><br>

<label>Select Food Items:</label><br>


<input type="checkbox" name="food_items[]" value="Pizza"> Pizza<br>
<input type="checkbox" name="food_items[]" value="Burger"> Burger<br>
<input type="checkbox" name="food_items[]" value="Pasta"> Pasta<br>
<input type="checkbox" name="food_items[]" value="Fries"> Fries<br>
<input type="checkbox" name="food_items[]" value="Biryani"> Biryani<br><br>

<label>Payment Method:</label>
<select name="payment" required>
<option value="">--Select--</option>
<option value="Cash on Delivery">Cash on Delivery</option>
<option value="UPI">UPI</option>
<option value="Credit/Debit Card">Credit/Debit Card</option>
</select><br><br>

<button type="submit">Place Order</button>


</form>
</body>
</html>
-----------------------
CREATE TABLE food_orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(100),
phone VARCHAR(20),
address TEXT,
food_items TEXT,
payment VARCHAR(50)
);
================
exam registration
<?php
// Step 1: Connect to MySQL
$servername = "localhost";
$username = "root";
$password = "";
$database = "university";

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Step 2: Get Form Data


$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];

// Step 3: Insert Data into Database


$sql = "INSERT INTO student (name, email, phone) VALUES ('$name', '$email', '$phone')";

if ($conn->query($sql) === TRUE) {


echo "Registration successful!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close the connection


$conn->close();
?>
------------
<!DOCTYPE html>
<html>
<head>
<title>Exam Registration</title>
</head>
<body>
<h2>Exam Registration Form</h2>
<form action="submit.php" method="POST">
<label>Name:</label>
<input type="text" name="name" required><br><br>

<label>Email:</label>
<input type="email" name="email" required><br><br>

<label>Phone:</label>
<input type="text" name="phone" required><br><br>

<button type="submit">Register</button>
</form>
</body>
</html>
==============================
library
CREATE TABLE library_card (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
address VARCHAR(255) NOT NULL,
dob DATE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
---------------------
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "university";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$dob = $_POST['dob'];

$sql = "INSERT INTO library_card (name, email, address, dob) VALUES ('$name', '$email',
'$address', '$dob')";

if ($conn->query($sql) === TRUE) {


echo "Library card application submitted!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

------------
<!DOCTYPE html>
<html>
<head>
<title>Library Card Application</title>
</head>
<body>
<h2>Library Card Application Form</h2>
<form action="library_submit.php" method="POST">
<label>Name:</label>
<input type="text" name="name" required><br><br>

<label>Email:</label>
<input type="email" name="email" required><br><br>
<label>Address:</label>
<input type="text" name="address" required><br><br>

<label>Date of Birth:</label>
<input type="date" name="dob" required><br><br>

<button type="submit">Apply</button>
</form>
</body>
</html>

=================
bank
CREATE TABLE bank_accounts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
phone VARCHAR(15) NOT NULL,
account_type ENUM('Savings', 'Current') NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-------------
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "university";

$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$account_type = $_POST['account_type'];

$sql = "INSERT INTO bank_accounts (name, email, phone, account_type) VALUES


('$name', '$email', '$phone', '$account_type')";

if ($conn->query($sql) === TRUE) {


echo "Bank account application submitted!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

-------
<!DOCTYPE html>
<html>
<head>
<title>Bank Account Application</title>
</head>
<body>
<h2>Bank Account Opening Form</h2>
<form action="bank_submit.php" method="POST">
<label>Name:</label>
<input type="text" name="name" required><br><br>

<label>Email:</label>
<input type="email" name="email" required><br><br>

<label>Phone:</label>
<input type="text" name="phone" required><br><br>

<label>Account Type:</label>
<select name="account_type" required>
<option value="Savings">Savings</option>
<option value="Current">Current</option>
</select><br><br>

<button type="submit">Open Account</button>


</form>
</body>
</html>

===============
ecommerce
CREATE TABLE ecommerce_orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
product_name VARCHAR(100) NOT NULL,
quantity INT NOT NULL,
address VARCHAR(255) NOT NULL,
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
----------
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "university";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$customer_name = $_POST['customer_name'];
$email = $_POST['email'];
$product_name = $_POST['product_name'];
$quantity = $_POST['quantity'];
$address = $_POST['address'];

$sql = "INSERT INTO ecommerce_orders (customer_name, email, product_name, quantity,


address)
VALUES ('$customer_name', '$email', '$product_name', '$quantity', '$address')";

if ($conn->query($sql) === TRUE) {


echo "Order placed successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

------------------
<!DOCTYPE html>
<html>
<head>
<title>E-Commerce Order Form</title>
</head>
<body>
<h2>Place an Order</h2>
<form action="ecommerce_submit.php" method="POST">
<label>Customer Name:</label>
<input type="text" name="customer_name" required><br><br>

<label>Email:</label>
<input type="email" name="email" required><br><br>

<label>Product Name:</label>
<input type="text" name="product_name" required><br><br>

<label>Quantity:</label>
<input type="number" name="quantity" required><br><br>

<label>Shipping Address:</label>
<input type="text" name="address" required><br><br>
<button type="submit">Order Now</button>
</form>
</body>
</html>

================
course
CREATE TABLE course_registration (
id INT AUTO_INCREMENT PRIMARY KEY,
student_name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
course_name VARCHAR(100) NOT NULL,
semester VARCHAR(50) NOT NULL,
registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
--------------
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "university";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$student_name = $_POST['student_name'];
$email = $_POST['email'];
$course_name = $_POST['course_name'];
$semester = $_POST['semester'];

$sql = "INSERT INTO course_registration (student_name, email, course_name, semester)


VALUES ('$student_name', '$email', '$course_name', '$semester')";

if ($conn->query($sql) === TRUE) {


echo "Course registration successful!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

--------
<!DOCTYPE html>
<html>
<head>
<title>Course Registration</title>
</head>
<body>
<h2>Register for a Course</h2>
<form action="course_submit.php" method="POST">
<label>Student Name:</label>
<input type="text" name="student_name" required><br><br>

<label>Email:</label>
<input type="email" name="email" required><br><br>

<label>Course Name:</label>
<input type="text" name="course_name" required><br><br>

<label>Semester:</label>
<input type="text" name="semester" required><br><br>

<button type="submit">Register</button>
</form>
</body>
</html>

====================

UNIT 1
1. Basic Features of Ruby on Rails
Ruby on Rails (RoR) is a full-stack web application framework written in Ruby.
It follows the Model-View-Controller (MVC) architecture and emphasizes
Convention over Configuration.
Key Features
1. Model-View-Controller (MVC) Architecture
o Model: Handles data and business logic.
o View: UI part that users interact with.
o Controller: Bridges model and view, handles user input.

Flow of MVC in Rails Example


Suppose a user visits /products/1
1. Router directs the request to:
o ProductsController#show
2. Controller fetches data:
o @product = Product.find(1)
3. Model (Product) interacts with the database to retrieve product with ID 1.
4. Controller passes @product to the view.
5. View renders show.html.erb with the product’s details.
6. The user sees the final HTML page in the browser.

Benefits of MVC
Benefit Explanation
Separation of
Easier to manage, debug, and scale
concerns
Reusability Same model can be used in multiple views
Backend and frontend developers can work
Easier collaboration
simultaneously
DRY Principle Code reuse via shared models and views

2. Convention over Configuration (CoC)


Rails provides default conventions, reducing the need for manual
configuration.
3. Active Record ORM
Handles database interactions using object-relational mapping. For
example:

class User < ApplicationRecord


end

User.create(name: "Alice")
4. RESTful Design
Rails encourages REST principles for clean URLs and actions (index,
show, create, update, destroy).
5. Scaffolding
Quickly generate MVC code for any resource:
rails generate scaffold Post title:string body:text
6. Built-in Testing Framework
MiniTest is integrated; supports unit, functional, and integration tests.
7. Gems & Plugins
Use gem install or define gems in Gemfile. Example:
gem 'devise' # authentication gem

Structure of a Ruby Program – Explained in Detail


Ruby is a clean, readable, and object-oriented scripting language. Its structure is
simple and intuitive, yet powerful enough to support complex applications like
those built in Ruby on Rails.

Key Components of a Ruby Program


Let’s break down the structure of a typical Ruby program:

1. Comments
Used to annotate code. Not executed.
• Single-line comment: Starts with #
• Multi-line comment: Between =begin and =end
# This is a single-line comment

=begin
This is a
multi-line comment
=end

2. Require and Load Statements


Used to include external files or libraries.
require 'date' # Loads Ruby's built-in Date library
require_relative 'math_utils' # Loads a file in the same directory

3. Classes and Modules


Encapsulate logic and define objects or namespaces.
class Person
def initialize(name)
@name = name
end
def greet
puts "Hello, I'm #{@name}"
end
end

4. Methods (Functions)
Reusable blocks of code.
def say_hello(name)
puts "Hello, #{name}!"
end

say_hello("Alice") # Output: Hello, Alice!

5. Control Structures
Conditionals and loops to control flow.
age = 20
if age >= 18
puts "Adult"
else
puts "Minor"
end
# Loop
5.times do |i|
puts "Count: #{i}"
end

6. Variables and Constants


• Variables: x = 10
• Constants: Start with a capital letter → PI = 3.14
name = "Ruby"
VERSION = "3.1.2"

7. Main Execution Block


Code not inside a class or method gets executed directly.
puts "Program started"

def greet
puts "Welcome to Ruby"
end

greet

Example: A Full Ruby Program


# greeting.rb

# Require built-in library


require 'date'

# Define a constant
APP_NAME = "GreetingApp"

# Define a class
class Greeter
def initialize(name)
@name = name
end

def greet
puts "Hello, #{@name}!"
puts "Today's date: #{Date.today}"
end
end

# Create an object and call a method


puts "Welcome to #{APP_NAME}"
g = Greeter.new("Alice")
g.greet
Output:
Welcome to GreetingApp
Hello, Alice!
Today's date: 2025-05-01

Summary Table of Ruby Program Structure


Component Purpose
Comments Code documentation
Require/Require_Relative Importing libraries or files
Classes Encapsulating logic and data
Methods Defining reusable blocks of code
Variables/Constants Storing data
Control Structures Conditional logic and loops
Main Execution Directly executed code at runtime

Gems, Gemfile, and how to use Gems in Ruby


A gem in Ruby is a packaged library or tool that provides functionalities to
enhance or add features to Ruby programs. It allows developers to share and
reuse code.
A Gemfile is a file used in Ruby projects to specify the gems and their versions
required for the project. It ensures consistency across different environments.
Procedure to Include a Gem in a Ruby Script:
1. Install the Gem:
gem install gem_name
2. Create a Gemfile: Add required gems:
source "https://rubygems.org"
gem "gem_name"
3. Install Gems from Gemfile: Run:
bundle install
4. Use the Gem in Script: Require the gem in the Ruby script:
require "gem_name"
5. Run the Script: Execute the Ruby script:
ruby script_name.rb

What Are Gems in Ruby?


Gems are packages or libraries that extend Ruby’s functionality. They allow
you to use pre-written code for common tasks like web scraping, date/time
manipulation, authentication, etc.
Each gem has:
• A name
• A version
• A functionality or module it provides
Managed using the RubyGems package manager.

What is a Gemfile?
A Gemfile is used in Ruby projects (especially with Bundler) to:
• List required gems
• Specify gem versions
• Ensure consistency across environments
Sample Gemfile:
source "https://rubygems.org"

gem "colorize"
gem "httparty"

Steps to Use a Gem in a Ruby Script


Step Action Command/Example
1 Install the gem gem install gem_name
2 Create a Gemfile (if using bundler) bundle init then edit Gemfile
3 Install all listed gems bundle install
4 Require the gem in your Ruby script require 'gem_name'
5 Use the gem's methods or features As per gem documentation

Example: Using the colorize Gem


The colorize gem adds color to terminal output.
Install the gem:
gem install colorize

Example Ruby Script (color_demo.rb):


# Require the gem
require 'colorize'

puts "This is red".colorize(:red)


puts "This is blue with white background".colorize(:color => :blue, :background
=> :white)
puts "This is green and underlined".colorize(:green).underline

Output (on a compatible terminal):


(This line will appear in red text)
(This line will appear in blue text with a white background)
(This line will appear in green and underlined)
Note: Output coloring appears only in terminals that support ANSI colors (like
Unix terminals, VS Code terminal, etc.)

Example: Gemfile + Ruby Script


Gemfile:
source "https://rubygems.org"
gem "colorize"
Terminal Commands:
bundle install
ruby color_demo.rb

Benefits of Using Gems


• Saves time by reusing tested code
• Increases productivity with wide library support
• Easy to manage dependencies with Gemfile and Bundler

Commonly Used Gems


Gem Purpose
colorize Terminal text styling
httparty HTTP requests and APIs
nokogiri HTML/XML parsing
sinatra Lightweight web applications
devise Authentication in Rails
pry Interactive debugging

What is CGI?
CGI (Common Gateway Interface) is a standard protocol that allows web
servers to execute external scripts or programs and use their output (usually
HTML) as a response to the client (browser).
CGI is used to create dynamic web content, such as processing forms, handling
queries, or interacting with databases.

How CGI Works (Simple Flow)


Browser (Client)
|
| HTTP Request
v
Web Server (e.g., Apache)
|
| Executes CGI Script
v
CGI Program (e.g., written in Ruby, Perl, Python)
|
| Output (HTML/JSON)
v
Web Server -> Browser

Integrating a CGI Script Using a Web Server


Here’s a step-by-step example of setting up a CGI script in Ruby using the
Apache web server.

Step 1: Install and Configure Apache


Install Apache (Linux example):
sudo apt install apache2
Enable CGI module:
sudo a2enmod cgi
sudo systemctl restart apache2
Ensure cgi-bin directory is enabled in /etc/apache2/sites-enabled/000-
default.conf:
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI
AddHandler cgi-script .cgi .rb .pl
Require all granted
</Directory>

Step 2: Create a CGI Script


Save the Ruby script as /usr/lib/cgi-bin/hello.rb:
#!/usr/bin/env ruby

puts "Content-Type: text/html\n\n"


puts "<html><body><h1>Hello from Ruby CGI!</h1></body></html>"
Make it executable:
sudo chmod +x /usr/lib/cgi-bin/hello.rb

Step 3: Access via Browser


Open your browser and go to:
http://localhost/cgi-bin/hello.rb

Output:
Hello from Ruby CGI!

Example:
Here’s a complete CGI script in Ruby that accepts input from an HTML form
and displays a greeting.

Step-by-Step CGI Script Example

1. HTML Form (form.html)


Save this file in your web server's document root (e.g.,
/var/www/html/form.html for Apache):
<!DOCTYPE html>
<html>
<head>
<title>CGI Form Example</title>
</head>
<body>
<h2>Enter Your Name</h2>
<form action="/cgi-bin/greet.rb" method="get">
<label>Name: </label>
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>

2. CGI Script in Ruby (/usr/lib/cgi-bin/greet.rb)


#!/usr/bin/env ruby
require 'cgi'

cgi = CGI.new
name = cgi['name']

puts "Content-Type: text/html\n\n"


puts "<html>"
puts "<head><title>Greeting</title></head>"
puts "<body>"
puts "<h1>Hello, #{CGI.escapeHTML(name)}!</h1>"
puts "<p>This message was generated using a Ruby CGI script.</p>"
puts "</body>"
puts "</html>"

3. Make Script Executable


sudo chmod +x /usr/lib/cgi-bin/greet.rb

4. Run the Script


1. Open a browser.
2. Navigate to:
3. http://localhost/form.html
4. Enter a name and submit.
5. You will see a greeting like:
Hello, Alice!
This message was generated using a Ruby CGI script.

Key Points
Component Description
#!/usr/bin/env ruby Shebang to use Ruby interpreter
Content-Type: CGI must output HTTP headers first
puts statements Generate HTML response
Executable permission Required for web server to run the script

How to Integrate CGI Script Using a Web Server


1. Set Up the Web Server:
o Install a web server like Apache or Nginx.
o Ensure CGI execution is enabled. For example, in Apache, enable
the mod_cgi module.
2. Write a CGI Script:
o Save the script in the web server's cgi-bin directory or the directory
configured for CGI execution.
o Example in Ruby:
#!/usr/bin/env ruby
puts "Content-Type: text/html\n\n"
puts "<html><body><h1>Hello,
CGI!</h1></body></html>"
3. Set Permissions:
o Make the script executable:
chmod +x script_name.rb
4. Configure the Web Server:
o Ensure the server allows CGI scripts in the specified directory.
o For Apache:
<Directory "/path/to/cgi-bin">
Options +ExecCG

Sample CGI Script with Form Handling (in Ruby):


#!/usr/bin/env ruby
require 'cgi'

cgi = CGI.new
name = cgi['name']

puts "Content-Type: text/html\n\n"


puts "<html><body>"
puts "<h1>Hello, #{name}!</h1>"
puts "</body></html>"
Call this via a form:
<form method="get" action="/cgi-bin/hello.rb">
<input type="text" name="name">
<input type="submit" value="Say Hello">
</form>

4.What is web server . explain types of webserver?


What is a Web Server?
A web server is software or hardware that processes and serves web pages to
users over the internet or an intranet. It handles incoming HTTP (or HTTPS)
requests from clients (such as web browsers) and delivers the requested
resources, which may include HTML files, images, CSS, JavaScript, or
dynamically generated content from server-side applications.
Web servers play a crucial role in hosting websites and applications, ensuring
accessibility, performance, and security.
Types of Web Servers
Web servers can be classified into different types based on their functionality
and architecture:
Static Web Servers
✅ Serve pre-built HTML, CSS, JavaScript, and images without modification.
✅ Do not process dynamic content or execute server-side scripts.
✅ Ideal for simple websites, documentation pages, and content delivery.
Examples:
Nginx (when serving static files)
Apache HTTP Server (configured for static content)
2️Dynamic Web Servers
✅ Serve dynamic content by processing server-side scripts before sending the
response to the client.
✅ Integrates with databases, application logic, and frameworks to generate
content on the fly.
✅ Used for interactive websites, e-commerce platforms, and CMS (e.g.,
WordPress, Django, Laravel).
Examples:
Apache HTTP Server (with PHP, Python, or Ruby)
Microsoft IIS (Internet Information Services)
LiteSpeed Web Server
3Application Servers
✅ Designed to execute server-side business logic and serve web applications
rather than just static content.
✅ Supports multi-tier architecture by interacting with databases, authentication
services, and other backend components.
✅ Used for enterprise-level applications, Java-based services, and API-driven
apps.
🔹 Examples:
Node.js (for JavaScript-based applications)
Apache Tomcat (for Java applications)
JBoss (WildFly) (for enterprise applications)
4️.Cloud-Based Web Servers
✅ Hosted on cloud platforms, providing scalability, high availability, and
distributed computing.
✅ Can handle sudden traffic spikes using auto-scaling and load balancing.
✅ Used for modern web applications, microservices, and global content
delivery.
🔹 Examples:
AWS Elastic Beanstalk
Google App Engine
Microsoft Azure App Service
5️. Reverse Proxy Servers
✅ Acts as an intermediary between clients and backend web servers.
✅ Improves security, performance, and load balancing by distributing traffic.
✅ Often used for caching, SSL termination, and DDoS protection.
Examples:
Nginx (as a reverse proxy and load balancer)
HAProxy (for high availability and load balancing)
Varnish Cache (for web acceleration and caching)
Other Notable Web Servers
Caching Web Servers – Store and serve frequently requested content to improve
response time (e.g., Varnish, Squid).
Secure Web Servers – Focus on encryption and cybersecurity (e.g., Caddy,
OpenLiteSpeed).
Embedded Web Servers – Used in IoT devices and small-scale applications
(e.g., Apache Tomcat Embedded).

5.Explain in detail about ruby toolkit?


The Ruby toolkit refers to the collection of tools, libraries, and frameworks
available in the Ruby ecosystem that facilitate application development. It
includes:
Key Components of the Ruby Toolkit
Ruby Language:
A dynamic, object-oriented scripting language with an emphasis on
simplicity and productivity.
Ruby Gems:
Gems are packages that provide specific functionality (e.g.,
authentication, APIs).
Managed via the Gemfile and bundler.
Frameworks:
Ruby on Rails: A web application framework.
Sinatra: Lightweight web development framework.
Hanami: Modular and faster framework for complex apps.
Libraries:
For testing: RSpec, Minitest.
For database access: ActiveRecord, Sequel.
Development Tools:
IRB (Interactive Ruby): For interactive coding.
Pry: Enhanced REPL with debugging.
Rake: Automation and task management.
Web Servers:
Puma, WEBrick, and Unicorn to serve Ruby apps.
Testing Frameworks:
Tools like Capybara for UI tests and RSpec for unit testing.
Package Management:
Bundler handles dependency management.
o 7. Explain basic OOP Concept in Ruby with Example?

Ruby is a pure object-oriented programming language where


everything is an object, including primitive data types. The basic OOP
concepts in Ruby are:

1. Classes and Objects:


- Class is a blueprint for creating objects
- Objects are instances of a class

Example:
class Student
def initialize(name, age)
@name = name
@age = age
end
def display
puts "Name: #{@name}, Age: #{@age}"
end
end
student1 = Student.new("John", 20)
student1.display

2. Encapsulation:
- Binding data and methods together while hiding implementation
details
- Achieved through access modifiers (public, private, protected)
Example:
class BankAccount
def initialize(balance)
@balance = balance
end
private
def log_transaction
# implementation hidden
end
end

3. Inheritance:
- Creating new classes from existing ones
- Ruby supports single inheritance
Example:
class Animal
def speak
"Animal sound"
end
end
class Dog < Animal
def speak
"Bark!"
end
end

4. Polymorphism:
- Ability to respond differently based on the object type
- Achieved through method overriding and duck typing
Example:
class Cat < Animal
def speak
"Meow!"
end
end
# Polymorphic behavior
[Dog.new, Cat.new].each { |animal| puts animal.speak }

5. Abstraction:
- Showing only essential features while hiding background details
- Achieved through modules and abstract classes
o
8.Explain different types of Widgets classes of Ruby TK Canvas
and Events? (5 marks, CO2)
o Ruby/Tk provides a Canvas widget that allows drawing graphics
and creating various widget items. Here are the main widget
classes and events:
o Canvas Widget Classes:
o 1. Basic Shapes:
- `create_line(x1, y1, x2, y2)`: Creates a line
- `create_rectangle(x1, y1, x2, y2)`: Creates a rectangle
- `create_oval(x1, y1, x2, y2)`: Creates an oval/circle
- `create_polygon(x1, y1, x2, y2, ...)`: Creates a polygon
- `create_arc(x1, y1, x2, y2)`: Creates an arc

2. Text and Images:


- `create_text(x, y, text: "string")`: Creates text
- `create_image(x, y, image: image_obj)`: Displays an image

3. Interactive Widgets:
- `create_window(x, y, window: widget)`: Embeds other Tk widgets
- `create_button(x, y, text: "Click")`: Creates a button (though
usually embedded via create_window)

Canvas Events:
1. Mouse Events:
- `<Button-1>`: Left mouse button click
- `<Button-2>`: Middle mouse button
- `<Button-3>`: Right mouse button
- `<B1-Motion>`: Mouse drag with left button
- `<Double-Button-1>`: Double click

2. Keyboard Events:
- `<KeyPress>`: Any key pressed
- `<KeyPress-a>`: Specific key ('a') pressed
- `<Return>`: Enter key pressed

3. Widget Events:
- `<Enter>`: Mouse enters widget area
- `<Leave>`: Mouse leaves widget area

Example Usage:
require 'tk'
root = TkRoot.new { title "Canvas Example" }
canvas = TkCanvas.new(root).pack
# Create a rectangle
rect = canvas.create_rectangle(50, 50, 150, 150, fill: 'blue')
# Bind events
canvas.bind('Button-1') do |x, y|
canvas.itemconfigure(rect, fill: 'red')
end
canvas.bind('Button-3') do |x, y|
canvas.itemconfigure(rect, fill: 'green')
end
Tk.mainloop
EXAMPLE: (Sum of numbers box)

Full Ruby Tk Code: Sum of Two Numbers GUI


require 'tk'

# Create the main window


root = TkRoot.new { title "Sum of Numbers" }
root.geometry("300x250")

# Heading label
heading = TkLabel.new(root) do
text "Sum of Numbers"
font TkFont.new('times 16 bold')
pack { padx 10; pady 10 }
end

# Number 1 label and entry


num1_label = TkLabel.new(root) do
text "Number 1:"
font TkFont.new('helvetica 12')
pack { padx 10; pady 5 }
end

entry1 = TkEntry.new(root) do
width 25
font TkFont.new('helvetica 12')
pack { padx 10; pady 5 }
end

# Number 2 label and entry


num2_label = TkLabel.new(root) do
text "Number 2:"
font TkFont.new('helvetica 12')
pack { padx 10; pady 5 }
end

entry2 = TkEntry.new(root) do
width 25
font TkFont.new('helvetica 12')
pack { padx 10; pady 5 }
end

# Button to calculate sum


sum_button = TkButton.new(root) do
text "Sum"
font TkFont.new('helvetica 12 bold')
command {
num1 = entry1.get.to_f
num2 = entry2.get.to_f
sum = num1 + num2
result_label.text = "Result: #{sum}"
}
pack { padx 10; pady 10 }
end

# Label to display result


result_label = TkLabel.new(root) do
text "Result: "
font TkFont.new('helvetica 12 bold')
foreground "blue"
pack { padx 10; pady 10 }
end

# Start the Tk main event loop


Tk.mainloop

🧪 Output GUI Structure:


+-------------------------+
| Sum of Numbers |
| |
| Number 1: [__________] |
| Number 2: [__________] |
| [ Sum ] |
| Result: <value> |
+-------------------------+

💡 To Run:
1. Save as sum_gui.rb
2. Run in terminal:
3. ruby sum_gui.rb
Let me know if you'd like to:
• Add input validation for non-numeric values,
• Change the layout to grid style,
• Add Clear/Reset buttons.

---------------------------------------------------
UNIT – 5
TCL and TK: Unit 5 Detailed Explanation (Each Sub-topic ~300 Words)

1. TCL Structure and Syntax


TCL, or Tool Command Language, is a highly versatile scripting language used
primarily for embedded applications, test automation, and GUI development with the
TK toolkit. One of TCL’s most distinct features is its extremely simple and uniform
syntax. Every line in TCL is a command followed by its arguments. Commands are
parsed line-by-line, and arguments are separated by whitespace. The first word in a
line is interpreted as the command, while the remaining words are passed as
arguments. Commands are terminated either by a newline or a semicolon. This flat
syntax model makes the language easy to parse and evaluate.
TCL allows grouping of arguments using braces {} to prevent substitution or quotes
"" to allow substitution. Square brackets [] are used for command substitution, where
the enclosed command is executed and replaced by its result. TCL is whitespace-
sensitive, and incorrect spacing can lead to unexpected results. Commenting is done
using the # symbol. The language treats all data as strings internally, but this does not
limit its expressiveness due to the extensive set of built-in commands.
The entire control structure (if, while, etc.) is implemented as commands, unlike
traditional programming languages that have special syntactic rules. This leads to a
powerful and flexible scripting environment. Since commands return strings, they can
be nested, piped, and evaluated dynamically. TCL is highly introspective; it can
analyze and modify its own code during execution. This property makes it ideal for
applications requiring runtime code generation or dynamic evaluation. Overall, TCL’s
syntax is minimalistic, promoting quick scripting and ease of integration with C-based
applications. Its uniform structure and powerful evaluation model are some of its
strongest attributes.
Example:
set a 10
puts "Value of a is $a"
2. Variables and Data in TCL
TCL variables are dynamically typed and do not require any prior declaration. A
variable is created the moment a value is assigned using the set command. For
example, set name "Varshini" assigns the value "Varshini" to the variable name. TCL
stores all values as strings, even if the content appears numeric. This allows flexibility
but requires conversion when performing arithmetic using the expr command.
Variables are referenced with the dollar sign ($), like $name, to retrieve their values.
TCL supports scalar variables (single value), lists (ordered collections), and arrays
(associative key-value pairs). Lists are created using the list command and accessed
with lindex, llength, and manipulated using lappend, linsert, etc. Lists are central in
TCL because many command results and script arguments are returned as lists. Arrays
are handled using the array command and allow keys like strings or numbers. Array
access is done via parentheses, e.g., set ages(John) 25. They are useful when
unordered data needs to be stored and accessed quickly.
TCL also supports variable scope control through global and upvar, allowing access or
linkage to variables across procedures. There’s no distinction between types like in
other languages; instead, the context defines how the string value is interpreted. This
dynamic handling of variables is well-suited for automation scripts, configuration
systems, and embedding in C applications. TCL’s variable model supports ease of
programming, fast development, and rapid prototyping.
Example:
set name "Varshini"
set age 25
set fruits [list apple orange banana]
puts "First fruit: [lindex $fruits 0]"

3. Control Flow
Control flow in TCL is managed through standard programming constructs such as if,
while, for, foreach, and switch. These constructs are implemented as commands,
allowing consistency in the syntax. The if statement is used to evaluate conditions and
execute code blocks accordingly. The syntax includes optional elseif and else parts for
handling multiple conditions. Loops like while and for are used for repetitive
operations where a condition governs the iteration. foreach is used to iterate over list
elements.
Each control structure uses braces {} to group multiple commands into blocks. The
break and continue commands can be used within loops to exit early or skip to the
next iteration, respectively. These control flow elements are essential for decision-
making and looping in TCL scripts. The switch command acts like a multi-way
branch, checking a variable against multiple values and executing matching code
blocks. All of these constructs make TCL scripts expressive and suitable for
algorithmic problem solving.
Control structures in TCL enhance the dynamic nature of the language. Because
everything is a command, control constructs can be nested, passed as arguments, or
generated at runtime using eval. This allows advanced control over script execution
and supports development of modular, reusable code. Such constructs are especially
useful in GUI applications, test scripts, and automation tools, where different
outcomes must be managed programmatically.
Example:
set x 5
if {$x > 3} {
puts "x is greater than 3"
} elseif {$x == 3} {
puts "x is equal to 3"
} else {
puts "x is less than 3"
}

4. Data Structures in TCL


TCL uses strings internally to represent all data, but provides strong support for
constructing and managing structured data types such as lists and arrays. Lists in TCL
are ordered collections of elements and can store strings, numbers, or even nested
lists. The list command creates a list, and elements are separated by spaces. Indexing
in lists is zero-based. Commands like lindex, lrange, llength, lappend, and linsert are
used to access and manipulate list elements.
Arrays in TCL are associative arrays or hash maps, implemented using the array
command. Each array element is a name-value pair where the name acts as the key.
Keys can be strings or numbers. TCL arrays are ideal for scenarios where quick
lookup by key is needed. The command array names returns all keys, while array get
returns key-value pairs. Nested data structures can be simulated using carefully
formatted strings or by combining lists and arrays.
There are also extensions like dict introduced in later versions of TCL (8.5+) that offer
more structured dictionary-like data types with subcommands like dict get, dict set,
etc. These offer efficient storage and manipulation for key-value pairs and are more
powerful and safer than arrays in some use cases.
Example (List and Array):
set myList [list red green blue]
puts "Second color: [lindex $myList 1]"

set student(Alice) 85
set student(Bob) 90
puts "Alice's marks: $student(Alice)"

5. Input/Output in TCL
TCL provides basic yet powerful commands for handling input and output operations.
Standard output is typically handled using the puts command, which prints to the
console or a file. By default, puts prints to standard output, but it can also direct output
to files using file descriptors.
To read and write files, TCL uses the open, read, gets, and puts commands. Files must
first be opened using open with the appropriate mode: r for reading, w for writing, or a
for appending. The command returns a file handle used for subsequent operations.
Data can be read using gets (for line-by-line) or read (for full file content). Output is
done using puts. After the operations, it’s good practice to close the file using the
close command.
TCL also supports standard input using gets stdin variableName, which waits for user
input. File handling in TCL is straightforward and supports both text and binary data
(with the fconfigure command). These I/O capabilities are essential for building
practical scripts that interact with files, logs, or user inputs.
Example:
set fp [open "data.txt" w]
puts $fp "Hello from TCL!"
close $fp

set fp [open "data.txt" r]


set content [read $fp]
close $fp
puts "File content: $content"

6. Procedures in TCL
Procedures in TCL allow you to define reusable blocks of code, promoting modularity
and clarity in scripts. The proc command is used to create a procedure. Its basic syntax
is:
proc name {arg1 arg2 ...} {
body
}
The procedure’s name is followed by a list of arguments and a body enclosed in
braces {}. When the procedure is called, the provided arguments are passed in order to
the formal parameters. Inside the body, you can use control structures, variables, and
other procedures just like in the main script.
TCL procedures return the result of the last executed command by default.
Alternatively, you can explicitly return a value using the return command. TCL does
not perform strict type checking or argument count enforcement unless you handle it
manually. However, you can provide default values for arguments to make procedures
more flexible. This is done by specifying a list containing the argument name and
default value.
Variables inside a procedure are local by default. To access global variables, you must
use the global keyword. Similarly, the upvar command allows you to reference
variables from a higher scope, enabling more advanced manipulation of variables
between procedures.
Procedures are essential for organizing code in larger TCL applications, especially in
test scripts, GUI callbacks, and reusable toolkits. TCL’s introspection capabilities
allow dynamic procedure definition and modification at runtime, which adds a layer
of flexibility uncommon in many scripting languages.
Example:
proc greet {name {greeting "Hello"}} {
puts "$greeting, $name!"
}

greet "Varshini"
greet "Ajay" "Welcome"

7. String Handling in TCL


Strings are fundamental in TCL, and since all data types are internally represented as
strings, TCL provides a rich set of commands for string manipulation. Common string
operations include concatenation, comparison, searching, replacement, case
conversion, and trimming.
The string command is a multifunctional command that supports subcommands such
as string length, string compare, string first, string last, string index, string range,
string tolower, string toupper, and more. These commands allow you to perform
complex manipulations with ease. You can also use regexp and regsub for pattern
matching and substitution using regular expressions.
String formatting and parsing are essential for tasks like processing input, constructing
output, or interpreting command results. TCL also supports escaping characters using
backslashes and can evaluate embedded variables and commands in double-quoted
strings. When working with user inputs or file contents, string handling is often a core
part of any script.
Example:
set name "TCL Language"
puts "Length: [string length $name]"
puts "Uppercase: [string toupper $name]"
puts "Substring: [string range $name 0 2]"

8. Pattern Matching in TCL


Pattern matching in TCL is a powerful feature used for searching, validating, and
transforming strings. TCL provides two primary methods for pattern matching: string
match and regexp. These commands serve different use cases and support distinct
pattern styles.
The string match command uses simple glob-style pattern matching, similar to Unix
shell wildcards. It supports:
• * to match any sequence of characters,

• ? to match a single character,


• [abc] to match any one of the characters a, b, or c.
For example, string match "file*.txt" "file123.txt" returns true because the pattern
matches the string. This command is useful for basic filename matching or wildcard
searches.
For more advanced and flexible pattern matching, TCL provides regexp, which
supports full POSIX regular expressions. This allows for complex string validation
and extraction. regexp takes a regular expression, a target string, and optional variable
names to store matched substrings. It returns true if a match is found.
Another related command is regsub, used for substitution based on a regular
expression. It replaces occurrences of a pattern within a string and can also store the
result in a variable.
Regular expressions support:
• Character classes ([a-z], [0-9])
• Quantifiers (*, +, ?, {n,m})
• Anchors (^, $)
• Groups ((...)) for capturing
Examples:
tcl
CopyEdit
# Using string match
if {[string match "Hello*" "HelloWorld"]} {
puts "Match found"
}

# Using regexp
set email "[email protected]"
if {[regexp {^(\w+)@(\w+\.\w+)$} $email -> user domain]} {
puts "User: $user, Domain: $domain"
}

# Using regsub
set text "TCL is cool"
regsub {cool} $text "powerful" newText
puts $newText ;# Output: TCL is powerful
Pattern matching is essential in parsing, input validation, text processing, and scripting
logic. TCL's support for both basic and advanced patterns makes it suitable for a wide
range of scripting tasks.
TCL and TK: Unit 5 - Advanced Topics Detailed Explanation (Each Sub-topic
~300 Words)

9. File Handling in TCL


TCL offers robust file handling capabilities suitable for scripting, logging, and
automation purposes. File I/O operations revolve around opening a file, performing
read/write actions, and then closing the file. The open command is used to open files
and returns a file handle (or descriptor). Modes for opening include r (read), w (write),
and a (append). The file must be closed after operations using the close command to
free resources.
To write to a file, use puts with the file handle. Reading can be performed using gets
(line-by-line) or read (full content). TCL also provides eof to check if the end of a file
is reached. Binary mode can be enabled with fconfigure to handle non-text data. The
command file exists checks for file presence, and file delete removes files.
Standard input/output operations can be performed using stdin, stdout, and stderr.
Input from users is collected using gets stdin variable, which reads from the console.
TCL’s file handling supports buffered and unbuffered modes, which can be managed
via fconfigure.
File operations are vital in configuration parsing, logging, storing script outputs, and
automation scripts. TCL’s simplicity and string-based model make file handling
straightforward yet flexible.
Example:
set fp [open "log.txt" w]
puts $fp "This is a log entry."
close $fp

set fp [open "log.txt" r]


set content [read $fp]
close $fp
puts "Content: $content"

10. Advanced TCL


Advanced features in TCL enhance its capabilities for complex scripting and
embedded application development. These features include dynamic code evaluation,
introspection, error handling, and object-oriented extensions.
The eval command dynamically executes TCL code from a string. It’s useful for
building and executing code on-the-fly. uplevel and upvar enable advanced scope
manipulation, allowing procedures to modify variables in other stack frames.
Error handling is facilitated with the catch and try commands. catch runs a block of
code and catches errors, preventing the script from crashing. It returns a status code
and can be used with custom error messages. The newer try command (TCL 8.6+)
offers structured error handling with on error, on return, and finally blocks.
TCL’s introspective features allow scripts to inspect variables, procedures, and the
call stack at runtime using commands like info vars, info procs, and info level.
Metaprogramming is possible due to TCL’s string-based nature, making it easy to
manipulate and generate code dynamically.
Object-oriented programming (OOP) can be introduced using extensions like Itcl (incr
Tcl), which provides classes, objects, and inheritance. Advanced packages like TclOO
support OOP natively in modern TCL versions.
Advanced TCL enables scripting for real-time systems, test automation, dynamic
GUIs, and interpreters.
Example (Error Handling):
if {[catch {expr 10 / 0} result]} {
puts "Error: $result"
} else {
puts "Result: $result"
}

Here’s a detailed explanation of the advanced TCL commands eval, source, exec, and
uplevel, each around 300 words:

Eval Command in TCL


The eval command in TCL allows for dynamic execution of TCL code that is
constructed at runtime. It takes one or more arguments, which are treated as a list of
commands, and executes them as if they were part of the current script. This makes it
a powerful tool for scenarios where the code to be executed is not known in advance,
such as when you need to execute a command dynamically based on user input or
script generation.
The syntax of eval is straightforward:
eval command arguments
The arguments are concatenated into a single string and then executed as a TCL
command. One common use case is to evaluate a string of code, which may include
variable references, as if it were regular TCL code.
For example:
set cmd "puts Hello, World!"
eval $cmd
In this example, the eval command executes the puts command stored in the variable
cmd, resulting in the output Hello, World!.
eval is particularly useful for building complex commands dynamically, but it should
be used with caution, especially when dealing with user input. Malicious code injected
into the string being evaluated can lead to security vulnerabilities. Proper validation or
sanitization of inputs is recommended.
Example (dynamic code generation):
set x 10
set y 20
eval "set sum [expr $x + $y]"
puts $sum ;# Output: 30

Source Command in TCL


The source command is used in TCL to read and execute the contents of another TCL
script or file. It is a common method for modularizing TCL code and reusing
functionality across multiple scripts. When source is called, the contents of the file are
processed as though they were written in the current script.
The syntax of source is:
source filename
Where filename is the name of the script to be executed. This command is particularly
useful for including external libraries, configurations, or reusable code in a TCL
script.
For example:
# File: functions.tcl
proc greet {name} {
puts "Hello, $name!"
}
# Main script
source functions.tcl
greet "Alice" ;# Output: Hello, Alice!
Here, the source command includes the functions.tcl script, making the greet
procedure available in the main script.
Note: If the source file does not exist or has syntax errors, an error will be raised, so
error handling can be added when sourcing files. It's also a good practice to manage
the scope of variables and procedures when sourcing files to avoid accidental
overwriting.

Exec Command in TCL


The exec command allows you to run external system commands or applications from
within a TCL script. It executes the command as if it were running in a terminal or
command prompt, and it returns the output of that command as a string.
The syntax of exec is:
exec command arguments
Where command is the external program or command to be executed, and arguments
are the parameters passed to the command. If the command produces output, it is
captured and returned as a result.
For example:
set result [exec ls -l]
puts $result
In this example, the exec command runs the ls -l command (which lists files in long
format on Unix-like systems) and stores the result in the result variable. The output of
the ls -l command is then printed to the console.
exec is useful for integrating system-level operations, such as invoking external
scripts, managing files, or executing system utilities directly from within a TCL script.
Example (Running an external program):
set current_time [exec date]
puts "Current time: $current_time"

Uplevel Command in TCL


The uplevel command in TCL allows you to execute a command in a different stack
frame, effectively enabling you to control the scope in which a command is evaluated.
By default, TCL commands are executed in the current level of the call stack. The
uplevel command lets you move to a higher or lower stack frame and execute code
within that context.
The syntax of uplevel is:
uplevel level command
Where level is an integer that specifies how many stack frames up (positive values) or
down (negative values) to move, and command is the code to be executed in that
context.
For example:
proc outerProc {} {
set x 10
proc innerProc {} {
uplevel 1 {puts "Value of x is $x"}
}
innerProc
}

outerProc
Here, innerProc is defined within outerProc, and it uses uplevel to execute the
command in the scope of outerProc. The output will be Value of x is 10 because
uplevel 1 references the stack frame of outerProc, where x is defined.
The uplevel command is useful for manipulating variable scopes dynamically or for
executing commands from within procedures or callbacks that need access to a
different scope.
Example (Scope control):
set var 5
proc modifyVar {} {
uplevel 1 {set var 10}
}
modifyVar
puts $var ;# Output: 10

11. Namespaces in TCL


Namespaces in TCL are used to organize code, prevent naming conflicts, and support
modular programming. A namespace is a container for commands and variables.
Namespaces help manage large applications by separating different components
logically.
The namespace command is used to create and manage namespaces. To define a new
namespace:
namespace eval MyApp {
variable counter 0
proc increment {} {
variable counter
incr counter
}
}
Variables and procedures inside a namespace are accessed using qualified names like
MyApp::increment. namespace export allows certain procedures to be accessible
when the namespace is imported using namespace import.
TCL supports hierarchical namespaces using :: as a delimiter, enabling tree-structured
module design. This is useful in large systems or when combining third-party
libraries. Variables declared using variable inside a namespace persist like global
variables within that context.
Namespaces support encapsulation and reuse, critical in applications involving
multiple developers or shared libraries. They are commonly used in GUIs, plugins,
and framework development.
Example:
namespace eval MathLib {
proc square {x} {
return [expr {$x * $x}]
}
}
puts [MathLib::square 5]
12. Event-driven Programming in TCL
TCL’s event-driven model allows the script to respond to user actions, file changes, or
timer events. This is crucial for building responsive GUI applications or background
daemons. The core commands involved are after, fileevent, and vwait.
The after command schedules a script to be executed after a specified time delay. It
can also schedule repeated execution. The fileevent command sets up callbacks when
a file descriptor is readable or writable, often used in socket programming. vwait
blocks execution until a variable changes, useful for synchronizing events.
In GUI applications (via TK), event bindings connect user actions like button clicks or
key presses to handlers using the bind command. For instance, bind . <Button-1>
{puts "Mouse clicked"} responds to left mouse clicks.
TCL’s event loop automatically processes these events when the interpreter is idle.
This non-blocking design ensures the UI remains responsive. Custom events can also
be created by changing variables or setting timers.
Event-driven programming is foundational for interactive applications, real-time
monitoring, and networked systems.
Example:
after 2000 {puts "Executed after 2 seconds"}
vwait done
set done 1

13. TK Widgets
TK is TCL’s GUI toolkit, allowing the creation of desktop applications with native
look-and-feel. Widgets are the visual elements like buttons, labels, text boxes, etc.
Each widget is a command that creates a GUI element and supports configuration and
event binding.
Common widgets include:
• label: displays text

• button: performs an action when clicked


• entry: single-line text input
• text: multi-line text editor
• frame: container for grouping widgets
• canvas: for drawing shapes and graphics
• listbox: displays a list of selectable items
Widgets are placed inside a window using geometry managers: pack, grid, or place.
pack arranges widgets in blocks, grid aligns them in rows/columns, and place gives
absolute positioning.
Widgets are created with a name and then configured:
label .lbl -text "Welcome to TK"
pack .lbl
Event bindings are applied using bind, or through widget-specific options like -
command for buttons. The mainloop command starts the TK event loop to keep the
window active.
TK makes it easy to build cross-platform GUI applications with minimal code. It is
ideal for prototypes, teaching tools, and internal utilities.
Example:
button .b -text "Click Me" -command {puts "Button clicked!"}
pack .b

I will expand each of these topics to approximately 300 words as you requested.
Here’s a breakdown of the expanded content:

14. Trapping Errors in TCL


In TCL, errors are handled using the catch command, which acts as a mechanism for
trapping and managing exceptions in the script. The catch command allows TCL
scripts to safely handle errors and prevent the program from terminating unexpectedly.
It works by executing a command and catching any errors that occur during execution.
The syntax for catch is as follows:
catch {command} result
Here, command is the TCL command to be executed, and result stores the error
message or the result of the command if it executes successfully. The catch command
returns a status code of 0 if the command executes successfully and a non-zero value
if an error occurs. This enables developers to handle errors without breaking the flow
of execution.
In addition to catching errors, TCL provides the error command, which can be used to
manually generate an error. The error command terminates execution and returns an
error message to the caller. This is useful for raising exceptions in custom procedures
or validating input.
For more complex error handling, TCL supports try and finally blocks in combination
with catch, offering better control over resource cleanup and recovery.
Error handling is crucial in long-running scripts and interactive applications. By using
catch and error, TCL scripts can gracefully handle unexpected situations, ensuring that
the program continues running smoothly without crashing.
Example:
set result [catch {set x 10 / 0} msg]
if {$result != 0} {
puts "Error: $msg"
}

15. Event-Driven Programs in TCL


TCL supports event-driven programming, which is an essential concept for building
responsive applications, especially graphical user interfaces (GUIs) and interactive
scripts. Event-driven programming ensures that the application can respond to various
events without blocking the main execution thread. TCL provides several mechanisms
for handling events asynchronously.
One of the key commands for event handling is after, which schedules a command to
run after a specified delay. This is commonly used for implementing timers or
deferred actions in an application. The syntax for after is:
after time {command}
Where time is the delay in milliseconds, and command is the code to be executed.
This allows building applications that don’t freeze while waiting for a specific event
or action to occur.
Another useful command is fileevent, which allows you to respond to file I/O events
such as reading from a file or socket. By using fileevent, TCL scripts can interact with
external resources asynchronously. The syntax is:
fileevent channel event mask command
This is useful when working with sockets, files, or other external sources.
Lastly, the vwait command is employed to wait for a variable to be modified, making
it ideal for implementing conditions where the program must wait for a specific event
before proceeding. The vwait command is particularly useful for synchronizing tasks
in event-driven programs.
Event-driven programming in TCL ensures efficient resource management and
enhances user experience by enabling non-blocking operations and real-time
responsiveness in applications.
Example:
after 1000 {puts "One second passed"}
vwait v

16. Making Applications Internet Aware in TCL


TCL provides a built-in http package that enables applications to send and receive
HTTP requests. This functionality is essential for integrating with web services,
downloading content from the internet, or interacting with APIs. The http package is
powerful for making web-based applications that communicate with remote servers.
To make an HTTP request, you can use the http::geturl command, which retrieves
content from a specified URL. For example:
package require http
set url "http://example.com"
set response [http::geturl $url]
puts "Response: $response"
This command makes a simple GET request to the specified URL and retrieves the
response. The http::geturl command also supports asynchronous operations, where
you can specify a callback function that handles the response when it is received,
allowing other tasks to continue running while waiting for the response.
TCL’s http package can also be used for sending POST requests, handling cookies,
and working with different HTTP headers. It’s versatile for a wide range of internet-
based applications.
For applications requiring secure communication, the https protocol is supported,
enabling encryption over SSL/TLS. The http package integrates seamlessly with other
TCL features like event-driven programming, allowing asynchronous network
communication without blocking the main script.
This makes TCL a powerful tool for creating internet-aware applications such as chat
clients, web scrapers, or automated testing tools that interact with online services.
Example:
package require http
set url "https://jsonplaceholder.typicode.com/todos/1"
set result [http::geturl $url]
puts "Fetched JSON: $result"

16. Nuts and Bolts of Internet Programming in TCL


TCL provides extensive support for socket programming, enabling the creation of
networked applications such as servers and clients. The socket command is used to
create a network connection, and it works with both TCP and UDP protocols. The
general syntax for creating a socket is:
set socket [socket host port]
This command establishes a connection to a given host and port, and the resulting
socket can be used to send and receive data. To communicate with the socket, TCL
provides the gets and puts commands, which are used for reading from and writing to
the socket, respectively.
In addition to client-side operations, TCL supports server-side socket programming
through the accept command, which allows a server to listen for incoming
connections. After a client establishes a connection, the server can use gets and puts to
interact with the client.
This functionality enables the creation of applications like chat servers, file transfer
protocols, and even custom networking protocols. By combining socket programming
with event-driven mechanisms like fileevent, TCL can manage concurrent connections
efficiently.
For example, a simple TCP server in TCL can accept connections, read data from
clients, and respond accordingly. This makes TCL suitable for building custom
network applications without requiring complex dependencies or external libraries.
Example:
set server [socket -server acceptConnection 12345]

proc acceptConnection {client socket addr port} {


puts $socket "Hello, client!"
close $socket
}

17. Security Issues in TCL


Security in TCL is a critical concern, especially given its dynamic nature and support
for executing code at runtime. One of the primary risks is the use of eval and exec
commands, which can execute arbitrary code. If user input is not carefully validated,
this can lead to security vulnerabilities, such as remote code execution or command
injection attacks.
To mitigate these risks, TCL provides mechanisms like sandboxing through the safe
interpreter. The safe::interp command creates a restricted environment where only a
limited set of commands are available for execution. This is ideal for running
untrusted code without compromising the security of the host application.
Another important practice is input validation. Always sanitize inputs and use strict
control over the data that is passed to functions like eval and exec. Avoid executing
raw user input directly and instead process or filter it before use. This helps protect
your application from malicious code.
For applications that require robust security, you can also leverage encryption and
hashing algorithms available in TCL’s packages, such as tls for secure communication
over the network.
By using sandboxing, validating inputs, and restricting the execution of potentially
harmful commands, developers can ensure that their TCL applications remain secure.
Example:
# Using the safe interpreter
safe::interpCreate mySafeInterp
safe::eval $mySafeInterp {puts "Hello, world!"}

18. C Interface in TCL


TCL provides a robust C API that enables integration between TCL scripts and C-
based applications. This allows developers to call TCL commands from C code and
vice versa, facilitating seamless interaction between interpreted TCL code and
compiled C functions.
To integrate TCL with C, developers can use the Tcl_CreateCommand function to
expose C functions as TCL commands. This makes it possible to call C functions
within TCL scripts as if they were native TCL commands. For example, a C function
can be exposed to TCL as follows:
#include <tcl.h>

int myCFunction(ClientData clientData, Tcl_Interp *interp, int argc, const char


*argv[]) {
Tcl_SetResult(interp, "Hello from C", TCL_STATIC);
return TCL_OK;
}

int main() {
Tcl_Interp *interp = Tcl_CreateInterp();
Tcl_CreateCommand(interp, "myCFunction", myCFunction, NULL, NULL);
Tcl_Eval(interp, "myCFunction");
return 0;
}
This allows TCL scripts to call C functions and leverage the efficiency of compiled C
code while maintaining the ease of scripting provided by TCL.
The reverse is also possible. C programs can invoke TCL interpreters and evaluate
TCL scripts dynamically. The integration between TCL and C is commonly used in
applications that require a combination of scripting flexibility and performance.
This ability to integrate TCL with C makes it ideal for applications that need to
interface with system-level libraries, hardware, or other compiled code, offering the
best of both worlds—scripting ease and performance.
Example:
Tcl_Eval(interp, "puts {Hello from C to TCL!}");
I’ll expand these topics to around 300 words each for you. Here’s a breakdown for the
requested topics:

TK: TK-Visual Tool Kits


TK is a powerful GUI (Graphical User Interface) toolkit that is used in combination
with TCL for building desktop applications. It provides a set of tools for creating
windows, buttons, labels, text boxes, menus, and other graphical elements commonly
used in applications. Unlike many other GUI toolkits, TK is lightweight and easy to
use, which makes it a popular choice for developing cross-platform applications
quickly.
TK abstracts many of the complexities of windowing systems, enabling developers to
focus on the layout and logic of their applications. TK can be integrated with TCL
code, which acts as the underlying script that controls the application's behavior. It is
designed to work with a variety of platforms, including Windows, macOS, and Linux.
One of the main features of TK is its widget-based system. It provides a rich set of
widgets, such as buttons, checkbuttons, radio buttons, entry fields, and listboxes.
These widgets can be customized with various options, such as size, color, font, and
layout. Additionally, TK supports complex GUI components such as canvas, which
can be used to create graphics, charts, and even games.
TK’s simplicity and ease of use have made it the go-to toolkit for rapid development
of desktop applications, especially for small to medium-scale projects. Developers can
leverage TK’s wide array of widgets and tools to create interactive applications
without needing to write complex GUI code.
Example:
package require Tk
button .btn -text "Click Me" -command {puts "Button Clicked!"}
pack .btn

Fundamental Concepts of TK
The core concepts of TK revolve around creating and managing widgets, event
handling, and managing the geometry of the window. In TK, a widget is any visual
element that is part of the interface, such as a button, label, text box, etc. Widgets are
created in a hierarchical structure, meaning they can be contained within other widgets
to create complex layouts.
TK allows for geometry management through a system of layout managers such as
pack, grid, and place. The pack geometry manager places widgets in a linear fashion,
either vertically or horizontally, while grid allows for the placement of widgets in a
grid of rows and columns. The place manager gives precise control over the
positioning of widgets using x, y coordinates.
Another essential concept in TK is event handling. TK uses an event-driven model,
where actions like button clicks or key presses trigger events that are handled by
specific callback functions. This allows TK applications to be interactive and
responsive.
TK widgets also support a variety of configuration options that control their
appearance, behavior, and functionality. These options can be set when the widget is
created or updated later using commands. Widgets in TK can be bound to events, such
as mouse clicks or keyboard presses, to trigger specific behaviors.
Example:
pack [button .btn -text "Click Me"]
bind .btn <Button-1> {puts "Button clicked!"}

TK by Example
TK provides an intuitive and straightforward way to create GUIs using simple
examples. The basic structure of any TK application involves creating a main window,
adding widgets to it, and then starting the event loop to handle user interactions.
Below are a few common examples that demonstrate the functionality of TK in action.
1. Creating a Simple Window with a Button:
This example creates a simple window with a button that displays a message
when clicked.
package require Tk
button .btn -text "Click Me" -command {puts "Button Clicked!"}
pack .btn
2. Creating a Text Box and Label:
This example demonstrates how to create an entry widget and a label that
displays the text entered by the user.
package require Tk
entry .entry
label .label -text "Enter your name:"
button .btn -text "Submit" -command {
set name [.entry get]
.label configure -text "Hello, $name!"
}
pack .label .entry .btn
3. Working with Menus:
This example creates a simple menu with options to open, save, and quit.
package require Tk
menu .m
.m add command -label "Open" -command {puts "Open File"}
.m add command -label "Save" -command {puts "Save File"}
.m add command -label "Quit" -command {exit}
menu .mb -tearoff 0
.mb add cascade -label "File" -menu .m
pack .mb
These examples show how to build basic interactive applications quickly. TK's
intuitive syntax makes it a great choice for those new to GUI programming.

Events and Binding in TK


In TK, event-driven programming is at the heart of how applications respond to user
interactions. Events can be triggered by various actions such as mouse clicks,
keyboard presses, or window resizing. These events are captured using bindings,
which link an event (e.g., a mouse click) to a specific action or callback function.
Binding in TK is achieved using the bind command, which allows you to specify
which events should trigger specific actions. For example, a button click can trigger a
command to execute a function:
bind .btn <Button-1> {puts "Button clicked!"}
In this example, the bind command associates the <Button-1> event (which is a left-
click) with the action puts "Button clicked!". Binding can be done for various events
like key presses (<KeyPress>), mouse clicks (<Button-1>), and mouse movement
(<Motion>).
Additionally, events can be bound to specific widgets or globally to the entire
application. This flexibility allows developers to create dynamic and interactive
applications. Binding can also be extended to handle events such as motion, window
resize, or focus changes.
Bindings are powerful because they allow developers to define how their applications
respond to user input, making them interactive and responsive.
Example:
bind .btn <Button-1> {puts "Left Click!"}
bind .btn <Enter> {puts "Mouse Entered Button!"}

Perl-TK
Perl-TK is a set of Perl bindings to the TK toolkit, enabling the creation of GUI
applications in Perl, just like you would in TCL. It allows developers to use Perl's
syntax while utilizing the power and flexibility of the TK GUI toolkit. Perl-TK is
widely used in the Perl community for developing desktop applications with a
graphical interface.
Perl-TK is similar to TCL-TK in many respects, as it also provides a set of widgets
like buttons, labels, text fields, and menus, allowing for the rapid development of
cross-platform applications. One of the advantages of Perl-TK is that it combines
Perl's powerful text processing capabilities with the simplicity of TK’s GUI
development.
To use Perl-TK, you need to install the Tk module. Once installed, you can create a
basic GUI application using a syntax similar to TCL. Here’s an example of creating a
window with a button in Perl-TK:
use Tk;
my $mw = MainWindow->new;
$mw->Button(-text => "Click Me", -command => sub { print "Button Clicked!\n" })-
>pack;
MainLoop;
In this example, a button is created that prints a message when clicked. The MainLoop
method starts the event-driven loop, allowing the application to wait for user
interactions. Perl-TK allows developers to write GUI applications in Perl with ease,
combining the power of both languages.
Example:
use Tk;
my $mw = MainWindow->new;
$mw->Label(-text => "Hello, Perl-TK!")->pack;
$mw->Button(-text => "Exit", -command => sub { exit })->pack;
MainLoop;

UNIT -2
1. Memory Allocation in Ruby
In Ruby, memory allocation is managed by the Garbage Collector (GC),
which automatically allocates and deallocates memory to optimize performance.
However, understanding how memory allocation works in Ruby can help
developers write more efficient code.
Ruby allocates memory in two main ways:
a) Stack Memory (for local variables and function calls)
• Used for storing local variables, method call information, and control
flow.
• Automatically managed and released when methods return.
b) Heap Memory (for objects and dynamically allocated data)
• All Ruby objects (like strings, arrays, and hashes) are allocated on the
heap.
• The Garbage Collector (GC) reclaims unused objects to free up heap
memory. 2. Memory Allocation Techniques
a) Objects Allocation
In Ruby, every object is dynamically allocated on the heap:
ruby CopyEdit
str = "Hello, Ruby!" # Allocated on the heap num = 42 # Small integers
are immediate values (stored directly in variables)
b) Immediate Values (Optimized Memory Usage)
Certain objects are stored directly in registers or stack memory instead of the
heap:
• Fixnums (small integers)
• Symbols
• true, false, nil
puts 42.object_id # Same object ID for the same integer puts 43.object_id #
Different object ID
Since Fixnums are stored as immediate values, their object IDs follow a pattern.
c) Strings and Mutability
• Strings are stored in the heap.
• Immutable strings (freeze) reduce memory allocation.
ruby CopyEdit str1 = "Hello".freeze str2 = "Hello".freeze puts str1.object_id ==
str2.object_id # Optimized memory reuse
3. Garbage Collection in Ruby
a) Mark-and-Sweep Algorithm
• Ruby uses a Mark-and-Sweep garbage collection method.
• It marks active objects and sweeps unused objects from memory.
b) Generational Garbage Collection
Modern Ruby versions use a Generational GC (like RGenGC in MRI Ruby
2.1+) for efficiency:
• Young objects: Frequently allocated and collected quickly.
• Old objects: Long-lived objects collected less frequently.
c) Manual Garbage Collection Control
Ruby allows developers to trigger garbage collection manually:
Heap Memory Allocation in RUBY:
Ruby dynamically allocates memory from the heap when an object is created.
Examples of objects stored in heap memory include:
• Strings
• Arrays
• Hashes
• Custom objects (instances of classes)
• Procs and Lambdas Example: Heap Allocation
str1 = "Hello, World!" # Allocated on the heap arr = [1, 2, 3, 4, 5] # Stored on
the heap hash = { name: "Ruby", version: 3.1 } # Stored on the heap
Each of these objects is allocated memory in the heap.
2. Ruby’s Heap Memory Structure
Ruby’s heap is divided into:
1. Ruby Heap - Stores Ruby objects.
2. C Heap - Stores internal C structures (MRI Ruby is implemented
in C).
Memory Allocation Process
1. When a new object is created, Ruby looks for free slots in the heap.
2. If no free slot is available, Ruby expands the heap.
3. Garbage Collector (GC) periodically frees unused objects to
reclaim memory.
3. Heap Memory Optimization
a) Using Symbols Instead of Strings
• Strings are allocated on the heap each time they are created.
• Symbols are stored only once in memory.
ruby CopyEdit
str1 = "hello" str2 = "hello"
puts str1.object_id == str2.object_id # false (Different heap allocations)

sym1 = :hello sym2 = :hello puts sym1.object_id == sym2.object_id # true


(Same memory allocation)
b) Using freeze for Immutable Strings
• Prevents new heap allocations.
ruby CopyEdit frozen_str = "Hello".freeze
c) Modifying Objects in Place
• Avoid unnecessary object creation.
ruby CopyEdit
arr = [1, 2, 3] arr.map! { |x| x * 2 } # Modifies in place instead of creating a
new array
d) Clearing Large Objects When No Longer Needed
• Manually freeing memory when an object is no longer needed.
ruby CopyEdit
large_array = Array.new(100000) { "data" } large_array = nil # Allows GC to
reclaim memory
GC.start # Trigger GC manually (not recommended frequently)
4. Garbage Collection (GC) and Heap Management
Ruby's Garbage Collector (GC) automatically reclaims heap memory using
Mark-and-Sweep and Generational GC techniques.
You can inspect the GC and heap status:
ruby CopyEdit puts GC.stat # Show GC statistics
Manually Adjusting GC Behavior
• Disable GC temporarily for performance tuning:
Conclusion
• Heap memory stores dynamically allocated objects.
• Ruby efficiently manages heap memory using the Garbage
Collector (GC).
• Using symbols, frozen strings, and in-place modifications can
optimize memory allocation.
• Clearing large objects and monitoring memory usage help in
performance tuning.
RUBY Type System:
Ruby is also regarded as strongly-typed.
All objects have a type and whenever an object is sent a message, the runtime
checks that the object can respond to it.
The Ruby Type System Ruby is interpreted so it cannot use static typing.
Ruby is entirely dynamically typed.
n fact, it uses a simple system called duck typing.
However, variables have no type in Ruby. Any variable can refer to any object.
In this sense, Ruby variables are typeless.
Duck Typing
Ruby typing is commonly called Duck Typing.
Types are not checked until the code is executed.
You ask an object to do something. If it can it does, if it can’t, it throws an
exception.
"When I see a bird that walks like a duck and swims like a duck and quacks like
a duck, I call that bird a duck." -- James Whitcomb Riley
In this model, the class of an object does not matter, all that matters is what it
can do.
Ruby is strongly typed, and uses a form of dynamic typing called duck typing.
This is important to understand as we look further at polymorphism.
Ruby Type System
Ruby is a dynamically typed and duck-typed language with a flexible and
expressive type system. Unlike statically typed languages like Java or C++,
Ruby does not require explicit type declarations. 1. Key Characteristics of
Ruby's Type System
Dynamic Typing
• Variable types are determined at runtime, not at compile time.
• You don't need to specify types when defining variables.
ruby CopyEdit
x = 10 # Integer x = "Hello" # Now it's a String (Type changes at runtime)
Duck Typing
• "If it behaves like a duck and quacks like a duck, it must be a
duck."
• Ruby does not check types explicitly but instead checks if an object
responds to a method.
ruby CopyEdit
def make_sound(animal)
animal.speak # It doesn't matter what the object's type is, as long as it has a
`speak` method end

class Dog def speak puts "Woof!" end end

class Cat def speak puts "Meow!"


end end

make_sound(Dog.new) # Woof! make_sound(Cat.new) # Meow! Everything


is an Object
• In Ruby, everything is an object, including primitive types like
numbers and booleans.
ruby CopyEdit
puts 5.class # Integer puts "Ruby".class # String
puts true.class # TrueClass

2. Type Categories in Ruby


a) Primitive Data Types
Type Example
Integer 10, -5, 0
Float 3.14, -0.5
String "hello", 'world'
Symbol :name, :id
Boolean true, false
Nil nil (Represents "nothing") ruby CopyEdit puts :symbol.class # Symbol
puts nil.class # NilClass
b) Collection Types
Type Description
Array Ordered list of elements
Hash Key-value pairs ruby CopyEdit
arr = [1, 2, 3] # Array hash = {a: 1, b: 2} # Hash
c) Custom Types (Classes & Modules)
You can define your own types using classes and modules.
ruby CopyEdit class Car def drive puts "Driving..." end
end

my_car = Car.new puts my_car.class # Car


3. Type Checking and Conversion
a) Checking Types (.class, is_a?, kind_of?)
ruby CopyEdit puts 100.is_a?(Integer) # true puts "Ruby".is_a?(String) # true
puts [1, 2, 3].kind_of?(Array) # true
b) Type Conversion (Casting)
Method Converts To
to_i Integer
to_f Float
to_s String
to_a Array
to_h Hash
ruby CopyEdit
puts "42".to_i # 42 (String → Integer) puts 3.14.to_s # "3.14" (Float → String)
puts :hello.to_s # "hello" (Symbol → String)
4. Static Type Checking in Ruby (Optional)
Though Ruby is dynamically typed, RBS (Ruby Type Signatures) and Sorbet
can be used for static type checking. Example: Using RBS (Type
Annotations)
rbs
CopyEdit
# Define a method signature def add(x: Integer, y: Integer) -> Integer
Example: Using Sorbet for Type Checking
ruby CopyEdit
require 'sorbet-runtime'

extend T::Sig

sig { params(x: Integer, y: Integer).returns(Integer) } def add(x, y) x + y


end
puts add(2, 3) # Works fine puts add("2", 3) # Raises a type error
What Does "Embedding a Ruby Interpreter" Mean?
Think of it like this:
• Your main application is written in another language (like C or
C++).
• You “embed” Ruby inside it, so the Ruby interpreter runs within
your program.
• This lets you execute Ruby scripts or use Ruby functions directly
from your app.
1. Include Ruby headers
To embed Ruby, your C/C++ code must include Ruby's header files:
c
CopyEdit #include <ruby.h>
2. Initialize the Ruby interpreter
Before running Ruby code, initialize the interpreter:
c
CopyEdit ruby_init();
3. Evaluate Ruby code
You can run Ruby code like this:
c
CopyEdit
rb_eval_string("puts 'Hello from embedded Ruby!'");
This will execute the Ruby puts method.
4. Shutdown Ruby (optional)
If needed, you can cleanly exit Ruby:
c
CopyEdit ruby_cleanup(0);
Example (C Code Embedding Ruby)
c
CopyEdit
#include <ruby.h>

int main(int argc, char **argv) { ruby_init(); // Start Ruby


ruby_script("embedded"); // Name your Ruby script

rb_eval_string("puts 'Hello from Ruby!'"); // Run Ruby code

ruby_cleanup(0); // Optional cleanup return 0;


}
CopyEdit
gcc -o embed_ruby embed_ruby.c `ruby -rrbconfig -e 'print
RbConfig::CONFIG["LIBRUBYARG_SHARED"]'` -I/usr/include/ruby-3.0.0
Why Embed Ruby?
• Customization: Let users write Ruby scripts to control your app.
• Scripting logic: Use Ruby for parts of logic that change often.
• Flexibility: Ruby is easier to change than compiled code.

When Not to Use It?


• If performance is critical and you can't afford interpreter overhead.
• If your main app already uses a different scripting language like
Python or Lua.
What is "Extending Ruby"?
Ruby is a high-level, dynamic programming language that is often used for web
development and scripting. While it is powerful on its own, there are times
when you might want to improve performance or reuse existing C code. In such
cases, you can write parts of your Ruby application in C—this is known as
extending Ruby.

Why Use C with Ruby?


Performance: C is much faster than Ruby, so performance-critical code can be
moved to C.
Access to System-Level Features: C can interact with low-level system
resources and APIs.
Reusing Existing C Libraries: If a library is already written in C, you can wrap
it and use it in Ruby.
What Are Ruby Objects in C?
When you extend Ruby with C, you still want your C code to behave like Ruby
code. This means the C code should:
Create and manipulate Ruby objects,
Respond to Ruby methods,
Interact with Ruby’s garbage collector.
Ruby provides a C API that allows you to define Ruby classes and methods in
C. You can then compile the C code as an extension and load it in Ruby using
require.
The Jukebox Extension
The phrase "the Jukebox extension" likely refers to a specific example or
project where a music jukeboxlike system is implemented as a Ruby extension
written in C.
Such a project would typically involve:
Defining a Jukebox class in C,
Adding methods like add_song, play, or list_songs,
Managing internal data structures in C (e.g., arrays or linked lists for songs),
Exposing the functionality to Ruby so it feels like native Ruby code.
Folder Structure: jukebox/
├── jukebox.c
└── extconf.rb
1️. jukebox.c — The C code
#include "ruby.h"
// Define a method that prints "Playing music..." VALUE
jukebox_play(VALUE self) { printf(" Playing music from the jukebox...\n");
return Qnil;
}
// Init method called when Ruby loads the extension void Init_jukebox() {
VALUE Jukebox = rb_define_class("Jukebox", rb_cObject);
rb_define_method(Jukebox, "play", jukebox_play, 0);
}
2. extconf.rb — The Extension Builder require 'mkmf'
create_makefile('jukebox')
This script generates a Makefile needed to compile the C code into a Ruby
extension.
3️.Build and Use the Extension
Step-by-step in Terminal: # Navigate to the directory cd jukebox # Generate
Makefile ruby extconf.rb # Compile the extension
make
This will generate a jukebox.so file (shared object), which can be required in
Ruby.
4.Use It in Ruby
require './jukebox'
jb = Jukebox.new jb.play # Playing music from the jukebox...

You might also like