Skip to content

Perl Built-in Functions API

Perl built-in functions covering IO, strings, lists, files and definition checks.

1 class · 8 methods

Perl Built-ins

8 methods

Perl 核心内置函数集合。

print LIST

打印列表到标准输出或文件句柄。

Parameters

NameTypeDescription
listlist待打印项

Returns

成功返回 1

Example

perl
print "Hello, Perl\n";
print "sum = ", 1+2, "\n";
scalar(@arr) / scalar(keys %hash)

强制标量上下文,返回数组或哈希的元素个数。

Parameters

NameTypeDescription
array/hashaggregate数组或哈希

Returns

整数,元素个数

Example

perl
my @arr = (1, 2, 3);
print scalar(@arr);   # 3

my %h = (a => 1, b => 2);
print scalar(keys %h); # 2
split(/pattern/, expr)

按正则将字符串分割为列表。

Parameters

NameTypeDescription
patternregex分割正则
expressionscalar源字符串

Returns

列表,分割结果

Example

perl
my @parts = split(/,/, "a,b,c");
# ("a", "b", "c")

my @w = split(/\s+/, "hello world  perl");
join(sep, LIST)

用分隔符将列表拼接为字符串。

Parameters

NameTypeDescription
separatorscalar分隔符
listlist待拼接元素

Returns

字符串

Example

perl
my $s = join(", ", "a", "b", "c");
# "a, b, c"

my $line = join("\t", @fields);
map BLOCK LIST

对列表每个元素执行块,返回结果列表。

Parameters

NameTypeDescription
blockblock转换块,用 $_ 引用元素
listlist输入列表

Returns

列表,映射结果

Example

perl
my @doubled = map { $_ * 2 } (1, 2, 3);
# (2, 4, 6)

my @upper = map { uc($_) } ("a", "b");
grep BLOCK LIST

保留使块返回真的元素。

Parameters

NameTypeDescription
blockblock谓词块,用 $_ 引用元素
listlist输入列表

Returns

列表,过滤结果

Example

perl
my @even = grep { $_ % 2 == 0 } (1..10);
# (2, 4, 6, 8, 10)
open(FH, mode, file)

打开文件并关联到文件句柄。

Parameters

NameTypeDescription
filehandleFH文件句柄
modestring打开模式如 '<','>','>>'
filenamestring文件名

Returns

成功返回非零,失败返回假并设 $!

Example

perl
open(my $fh, '<', 'data.txt') or die "open: $!";
while (my $line = <$fh>) {
  chomp $line;
  print $line, "\n";
}
close($fh);
defined(expr)

判断值是否已定义(非 undef)。

Parameters

NameTypeDescription
exprscalar待检测值

Returns

布尔,已定义返回真

Example

perl
my $x;
print defined($x) ? "yes" : "no";   # no
$x = 0;
print defined($x) ? "yes" : "no";   # yes