Skip to content

Perl

Perl, created in 1987 - https://www.perl.org/

#!/usr/bin/perl
use strict;
use warnings;
print "=== Perl Demo: 11 Examples ===\n\n";
# 1. Hello World
print "1) Hello World:\n";
print "Hello, world!\n\n";
# 2. Variables and arithmetic
print "2) Variables & Arithmetic:\n";
my $a = 5;
my $b = 3;
print "a = $a, b = $b, sum = ", $a + $b, "\n\n";
# 3. Arrays
print "3) Arrays:\n";
my @fruits = ("apple", "banana", "cherry");
print "First fruit: $fruits[0]\n";
print "All fruits: @fruits\n\n";
# 4. Hashes
print "4) Hashes:\n";
my %ages = ("Alice" => 25, "Bob" => 30);
print "Alice is $ages{Alice} years old\n\n";
# 5. Conditionals
print "5) Conditionals:\n";
if ($a > $b) {
print "$a is greater than $b\n\n";
} else {
print "$b is greater or equal to $a\n\n";
}
# 6. Loops
print "6) Loops:\n";
for my $i (1..3) {
print "Loop iteration $i\n";
}
print "\n";
# 7. Subroutines (with @_ unpacking)
print "7) Subroutines:\n";
sub greet {
my ($name) = @_;
return "Hello, $name!";
}
print greet("Perl User"), "\n\n";
# 8. File handling
print "8) File Handling (write & read):\n";
my $filename = "demo.txt";
open(my $fh, ">", $filename) or die "Cannot open file: $!";
print $fh "This is a test file.\n";
close($fh);
open(my $rfh, "<", $filename) or die "Cannot read file: $!";
while (my $line = <$rfh>) {
print "Read: $line";
}
close($rfh);
print "\n";
# 9. Regular expressions
print "9) Regular Expressions:\n";
my $text = "Perl is powerful";
if ($text =~ /powerful/) {
print "Match found in text!\n\n";
}
# 10. Command-line arguments
print "10) Command-line Arguments:\n";
if (@ARGV) {
print "Arguments passed: @ARGV\n\n";
} else {
print "No arguments provided\n\n";
}
# 11. Function using shift
print "11) Function with shift:\n";
sub add_numbers {
my $x = shift; # first argument
my $y = shift; # second argument
return $x + $y;
}
my $result = add_numbers(10, 20);
print "10 + 20 = $result\n";
print "\n=== End of Demo ===\n";
  • “Programming Perl” - “Camel book” with a dromedary camel

Similar to Python and Ruby