Unit 3: Introduction To PERL and Scripting
Unit 3: Introduction To PERL and Scripting
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
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
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
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
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.
use strict;
use warnings;
use CGI;
my $cgi = CGI->new;
print $cgi->header('text/html');
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.
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
🔄 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
1. Conditional Structures
a) if, elsif, else
Syntax:
if (condition) {
# code block
} elsif (another_condition) {
# another block
} else {
# fallback block
}
Example:
my $age = 20;
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
d) foreach loop
Used to iterate through an array/list.
Example:
my @fruits = ("apple", "banana", "cherry");
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;
# Add elements
push(@fruits, "mango"); # Add to end
unshift(@fruits, "grape"); # Add to beginning
# Remove elements
my $last = pop(@fruits); # Remove last
my $first = shift(@fruits); # Remove first
# Array length
my $len = scalar @fruits;
print "Length of array: $len\n";
# Sort array
my @sorted = sort @fruits;
print "Sorted array: @sorted\n";
# Slice array
my @slice = @fruits[0, 1];
print "Sliced array (first two): @slice\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
✅ 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
Note
When used in scalar context, the list returns the last element of the list:
perl
CopyEdit
my $x = (10, 20, 30); # $x = 30
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.
Deleting Elements
delete $hash{"grape"};
my %colors = (
"apple" => "red",
"banana" => "yellow",
"grape" => "purple"
);
# Delete a key
delete $colors{"grape"};
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
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
tr/// - Transliteration
Changes specific characters:
my $msg = "hello";
$msg =~ tr/a-z/A-Z/; # Convert to uppercase
print "$msg\n"; # Output: HELLO
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;
sub greet {
print "Hello from subroutine!\n";
}
my $result = square(6);
print "Square: $result\n";
Output:
Square: 36
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";
}
# Calling subroutines
greet("John");
my $f = factorial(5);
print "Factorial: $f\n";
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.
Conditional Statements
Conditional statements execute a block of code based on whether a condition is
true or false.
📌 if, else, elseif
<?php
$age = 18;
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");
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
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.
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.";
}
?>
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,.
// 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");
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.
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";
}
$name = $_POST['name'];
$email = $_POST['email'];
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
$name = $_POST['name'];
$email = $_POST['email'];
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.
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)
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"]);
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);
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
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_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>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>
// Create a connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
<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')";
$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";
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$account_type = $_POST['account_type'];
$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>
===============
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'];
$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'];
$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.
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
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
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
4. Methods (Functions)
Reusable blocks of code.
def say_hello(name)
puts "Hello, #{name}!"
end
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
def greet
puts "Welcome to Ruby"
end
greet
# 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
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"
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.
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.
cgi = CGI.new
name = cgi['name']
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
cgi = CGI.new
name = cgi['name']
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
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)
# Heading label
heading = TkLabel.new(root) do
text "Sum of Numbers"
font TkFont.new('times 16 bold')
pack { padx 10; pady 10 }
end
entry1 = TkEntry.new(root) do
width 25
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
💡 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)
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"
}
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
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"
# 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)
Here’s a detailed explanation of the advanced TCL commands eval, source, exec, and
uplevel, each around 300 words:
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
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
I will expand each of these topics to approximately 300 words as you requested.
Here’s a breakdown of the expanded content:
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:
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.
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)
extend T::Sig