Perl 是一种功能强大的脚本语言,广泛应用于文本处理、系统管理、网络编程和 Web 开发。本文将带你入门 Perl 编程,涵盖基础语法、变量、控制结构、函数和文件操作等内容。
macOS 和大多数 Linux 发行版都预装了 Perl。你可以在终端中输入以下命令来检查 Perl 是否已安装:
perl -v
如果没有安装,可以使用包管理器来安装:
# 在 macOS 上使用 Homebrew 安装
brew install perl
# 在 Debian/Ubuntu 上使用 APT 安装
sudo apt-get install perl
# 在 CentOS/Fedora 上使用 YUM 安装
sudo yum install perl
使用你喜欢的文本编辑器创建一个名为 hello.pl
的文件,输入以下代码:
#!/usr/bin/perl
use strict;
use warnings;
print "Hello, world!\n";
保存文件后,在终端中运行该程序:
perl hello.pl
你应该会看到输出:
Hello, world!
Perl 支持三种类型的变量:标量、数组和哈希。
标量用于存储单一值,可以是字符串、数字或引用。标量变量以美元符号 $
开头。
my $name = "Alice";
my $age = 30;
my $pi = 3.14;
print "Name: $name\n";
print "Age: $age\n";
print "Pi: $pi\n";
数组用于存储有序列表,数组变量以 @
开头。
my @colors = ("red", "green", "blue");
print "First color: $colors[0]\n";
print "All colors: @colors\n";
哈希用于存储键值对,哈希变量以 %
开头。
my %fruit_colors = (
apple => "red",
banana => "yellow",
grape => "purple",
);
print "Apple is $fruit_colors{'apple'}\n";
Perl 提供了多种运算符,包括算术运算符、字符串运算符和比较运算符等。
my $sum = 5 + 3;
my $difference = 5 - 3;
my $product = 5 * 3;
my $quotient = 5 / 3;
my $remainder = 5 % 3;
print "Sum: $sum\n";
print "Difference: $difference\n";
print "Product: $product\n";
print "Quotient: $quotient\n";
print "Remainder: $remainder\n";
my $greeting = "Hello, " . "world!";
my $repeat = "ha" x 3;
print "$greeting\n";
print "$repeat\n";
==
, !=
, <
, >
, <=
, >=
eq
, ne
, lt
, gt
, le
, ge
my $num1 = 5;
my $num2 = 10;
if ($num1 == $num2) {
print "Numbers are equal\n";
} else {
print "Numbers are not equal\n";
}
my $str1 = "apple";
my $str2 = "banana";
if ($str1 eq $str2) {
print "Strings are equal\n";
} else {
print "Strings are not equal\n";
}
my $age = 20;
if ($age >= 18) {
print "Adult\n";
} else {
print "Minor\n";
}
while
循环my $count = 0;
while ($count < 5) {
print "Count: $count\n";
$count++;
}
for
循环for (my $i = 0; $i < 5; $i++) {
print "Iteration: $i\n";
}
foreach
循环my @numbers = (1, 2, 3, 4, 5);
foreach my $num (@numbers) {
print "Number: $num\n";
}
sub greet {
my ($name) = @_;
print "Hello, $name!\n";
}
greet("Alice");
sub add {
my ($a, $b) = @_;
return $a + $b;
}
my $result = add(5, 3);
print "Sum: $result\n";
my $filename = 'input.txt';
open(my $fh, '<', $filename) or die "Could not open file '$filename' $!";
while (my $line = <$fh>) {
chomp $line;
print "$line\n";
}
close($fh);
my $filename = 'output.txt';
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
print $fh "Hello, file!\n";
close($fh);
my $text = "The quick brown fox";
if ($text =~ /quick/) {
print "Text contains 'quick'\n";
}
my $text = "The quick brown fox";
$text =~ s/quick/slow/;
print "$text\n"; # The slow brown fox
my $text = "My phone number is 123-456-7890";
if ($text =~ /(\d{3})-(\d{3})-(\d{4})/) {
print "Area code: $1\n";
print "Main number: $2-$3\n";
}
Perl 拥有丰富的模块库,可以使用 CPAN(Comprehensive Perl Archive Network)来安装和管理模块。
cpan install Some::Module
use Some::Module;
# 使用模块提供的功能