Below are some simple examples in Perl to illustrate its syntax and capabilities:
**1. Hello World:**
```perl
#!/usr/bin/perl
use strict;
use warnings;
print "Hello, World!\n";
```
This is a basic "Hello, World!" script in Perl. It prints the string "Hello, World!" to the standard output.
**2. Variables and User Input:**
```perl
use strict;
use warnings;
print "Enter your name: ";
my $name = <STDIN>;
chomp($name); # Remove the newline character
print "Hello, $name!\n";
```
In this example, the program asks the user to enter their name, reads the input from the keyboard, and then prints a personalized greeting.
**3. Mathematical Operations:**
```perl
use strict;
use warnings;
my $a = 5;
my $b = 3;
my $sum = $a + $b;
my $difference = $a - $b;
my $product = $a * $b;
my $quotient = $a / $b;
print "Sum: $sum\n";
print "Difference: $difference\n";
print "Product: $product\n";
print "Quotient: $quotient\n";
```
This script demonstrates basic mathematical operations: addition, subtraction, multiplication, and division.
**4. Using Regular Expressions:**
```perl
use strict;
use warnings;
my $text = "The quick brown fox jumps over the lazy dog.";
if ($text =~ /fox/) {
print "The text contains 'fox'.\n";
}
if ($text =~ /cat/) {
print "The text contains 'cat'.\n";
} else {
print "The text does not contain 'cat'.\n";
}
```
In this example, we use regular expressions to search for specific patterns in a text. It checks whether the text contains the word "fox" and "cat."
**5. Conditional Statements:**
```perl
use strict;
use warnings;
my $number = 42;
if ($number == 42) {
print "The number is the answer to the Ultimate Question of Life, the Universe, and Everything.\n";
} else {
print "The number is not the answer.\n";
}
```
This script uses an `if` statement to check whether a variable is equal to 42 and prints a message accordingly.
These examples provide a glimpse of Perl's syntax and some of its basic features. Perl is known for its strong text processing capabilities and support for regular expressions, making it particularly useful for tasks involving text manipulation, data extraction, and system administration.