入门
基础与 Hello World
Perl 使用 sigil 表示变量类型:$ 表示标量,@ 表示数组,% 表示哈希。始终使用 strict 和 warnings 以获得更干净的代码。
#!/usr/bin/perl
use strict;
use warnings;
print "Hello, World!\n";
# variables: scalar ($), array (@), hash (%)
my $name = "Alice";
my @nums = (1, 2, 3);
my %ages = (Alice => 30, Bob => 25);
print "Name: $name\n";注释
单行注释以 # 开头。多行注释使用由 =pod 和 =cut 界定的 POD 块。POD 也用于文档编写。
#!/usr/bin/perl
# This is a single-line comment
print "Hello\n"; # inline comment
=pod
This is a multi-line
comment using POD (Plain Old Documentation)
=cut
print "After POD\n";标量简介
标量保存单个值:字符串、数字或引用。Perl 会在字符串和数字之间自动转换。用 . 连接字符串,用 x 重复字符串。
my $str = "Hello";
my $num = 42;
my $float = 3.14;
my $bool = 1; # true (0, "", "0", undef are false)
# String repetition
my $line = "-" x 20;
# String concatenation
my $greeting = "Hello, " . $str;
print "$greeting\n"; # Hello, Hello字符串插值
双引号字符串会插值 $ 和 @ 变量;单引号是字面量。当变量名后紧跟会扩展标识符的字符时,用花括号来界定变量名,例如表示复数。
my $name = "Alice";
my $age = 30;
print "Name: $name\n"; # interpolates
print 'Name: $name\n'; # literal (no interpolation)
# Disambiguate variable name with braces
my $fruit = "apple";
print "I have many ${fruit}s.\n"; # I have many apples.
# Array interpolation (joins with $")
my @arr = (1, 2, 3);
print "Array: @arr\n"; # Array: 1 2 3use strict 与 warnings
strict 强制词法作用域(my/our)并捕获拼写错误。warnings 启用有用的诊断信息。现代代码可用 'use v5.36'(或更高)一并启用这些与新特性。
use strict;
use warnings;
# Without strict, this would create a global:
# $foo = 42; # ERROR under strict
my $foo = 42; # OK with my
# Warnings catch common mistakes
my $undef_var;
# print $undef_var; # warns: uninitialized value
# Modern bundle (v5.36+ enables strict, warnings, features)
use v5.36;
# Disable specific warnings locally
no warnings 'uninitialized';say 与特性
say 类似 print 但自动追加换行。用 'use feature' 或版本束如 'use v5.36' 启用特性。签名特性提供命名参数,无需再解包 @_。
use v5.10;
use feature 'say';
say "Hello!"; # adds newline automatically
say "No need for \n";
# Equivalent to:
print "Hello!\n";
# Signatures (v5.20+, not default)
use feature 'signatures';
no warnings 'experimental::signatures';
sub greet ($name) {
say "Hi, $name";
}标量
数字与运算符
Perl 拥有完整的算术运算符。除法总是返回浮点数,除非用 int()。** 是幂运算。++ 和 -- 对数字和字符串都有效(自增 'a' 得到 'b')。
my $sum = 5 + 3; # 8
my $diff = 10 - 4; # 6
my $prod = 6 * 7; # 42
my $div = 10 / 3; # 3.3333...
my $int = int(10 / 3); # 3
my $mod = 10 % 3; # 1
my $pow = 2 ** 10; # 1024
# Augmented assignment
my $x = 5;
$x += 3; # $x = 8
$x **= 2; # $x = 64
$x++; # $x = 65
$x--; # $x = 64字符串运算符
用 . 连 接(不是 +),用 x 重复。字符串比较用 eq/ne/lt/gt;数字比较用 ==/!=/</>。混用可能产生意外结果。
my $a = "Hello";
my $b = "World";
# Concatenation
my $combined = $a . ", " . $b; # Hello, World
# Repetition
my $line = "=" x 30;
# Augmented concatenation
my $str = "abc";
$str .= "def"; # abcdef
# Numeric vs string comparison
print "match" if "abc" eq "abc"; # string equal
print "match" if 123 == 123; # numeric equalundef 与 defined
undef 表示未定义(或缺失)的值。用 defined() 检测它。//(defined-or)运算符仅当左边为 undef 时返回右边,而 || 还会在 0 或 '' 时触发。
my $x; # undef
print "undef\n" if !defined $x;
$x = undef; # explicitly undef
undef $x; # another way
# Defined-or operator
my $val = $x // "default";
# Warning if used as string:
# print $x; # Use of uninitialized value
if (defined $val) {
print "Defined: $val\n";
}引号 (q/qq/qw)
q// 是单引号,qq// 是双引号,qw// 按空白拆分为列表。可使用任意匹配定界符((), {}, [], //, !!),便于避免字符串内部的引号转义。
my $name = "Alice";
# q() = single quote (no interpolation)
my $s1 = q(Hello $name); # Hello $name
# qq() = double quote (interpolation)
my $s2 = qq(Hello $name); # Hello Alice
# qw() = quoted words (produces a list)
my @words = qw(apple banana cherry);
# equivalent to ("apple", "banana", "cherry")
# Custom delimiters
my $s3 = q{don't worry};
my $s4 = q!bang!;Here 文档
Heredoc 用于编写多行字符串。<<'END' 是字面量(无插值),<<"END" 会插值。~ 变体(v5.26+)去除前导空白,使 heredoc 可与周围代码一起缩进。
my $name = "Alice";
# Single-quote style (no interpolation)
my $text = <<'END';
Hello $name,
This is literal.
END
# Double-quote style (interpolation)
my $msg = <<"EOF";
Hello $name,
Interpolated here.
EOF
print $msg;
# Indented heredoc (v5.26+)
my $code = <<~EOT;
line 1
line 2
EOT布尔真值
只有 undef、0、'' 和 '0' 为假;连 '00' 和 '0.0' 都是真!用 || 设真值默认,用 // 设已定义默认。引用(即使是空数组)始终为真。
# False values: undef, 0, "", "0"
# Everything else is true
print "true\n" if 1; # true
print "true\n" if "hello"; # true
print "true\n" if "0"; # NOT printed (false!)
print "true\n" if ""; # NOT printed (false)
print "true\n" if []; # true (reference is true)
# Logical operators
my $x = 0 || "default"; # default (|| tests truthiness)
my $y = 0 // "default"; # default (// tests definedness)
my $z = "a" && "b"; # b (returns last evaluated)数组
数组基础
数组用 @ sigil 表示整个数组,用 $ 访问单个元素(因为元素是标量)。$#arr 给出最后索引。标量上下文中数组返回其长度。
my @nums = (1, 2, 3, 4, 5);
my @strs = qw(a b c);
my @mixed = (1, "two", 3.14);
# Access by index (0-based)
print $nums[0]; # 1
print $nums[-1]; # 5 (last element)
# Modify an element
$nums[0] = 100;
# Range operator
my @range = (1 .. 10); # 1 to 10
# Length in scalar context
my $count = scalar @nums; # 5
my $count2 = @nums; # 5push/pop/unshift/shift
push/pop 在末尾增删(快);unshift/shift 在开头增删(较慢,需重索引)。splice 是在任意位置增删替换的通用工具。