Perl Built-ins
8 methodsPerl 核心内置函数集合。
print LIST打印列表到标准输出或文件句柄。
Parameters
| Name | Type | Description |
|---|---|---|
| list | list | 待打印项 |
Returns
成功返回 1
Example
perl
print "Hello, Perl\n";
print "sum = ", 1+2, "\n";scalar(@arr) / scalar(keys %hash)强制标量上下文,返回数组或哈希的元素个数。
Parameters
| Name | Type | Description |
|---|---|---|
| array/hash | aggregate | 数组或哈希 |
Returns
整数,元素个数
Example
perl
my @arr = (1, 2, 3);
print scalar(@arr); # 3
my %h = (a => 1, b => 2);
print scalar(keys %h); # 2split(/pattern/, expr)按正则将字符串分割为列表。
Parameters
| Name | Type | Description |
|---|---|---|
| pattern | regex | 分割正则 |
| expression | scalar | 源字符串 |
Returns
列表,分割结果
Example
perl
my @parts = split(/,/, "a,b,c");
# ("a", "b", "c")
my @w = split(/\s+/, "hello world perl");join(sep, LIST)用分隔符将列表拼接为字符串。
Parameters
| Name | Type | Description |
|---|---|---|
| separator | scalar | 分隔符 |
| list | list | 待拼接元素 |
Returns
字符串
Example
perl
my $s = join(", ", "a", "b", "c");
# "a, b, c"
my $line = join("\t", @fields);map BLOCK LIST对列表每个元素执行块,返回结果列表。
Parameters
| Name | Type | Description |
|---|---|---|
| block | block | 转换块,用 $_ 引用元素 |
| list | list | 输入列表 |
Returns
列表,映射结果
Example
perl
my @doubled = map { $_ * 2 } (1, 2, 3);
# (2, 4, 6)
my @upper = map { uc($_) } ("a", "b");grep BLOCK LIST保留使块返回真的元素。
Parameters
| Name | Type | Description |
|---|---|---|
| block | block | 谓词块,用 $_ 引用元素 |
| list | list | 输入列表 |
Returns
列表,过滤结果
Example
perl
my @even = grep { $_ % 2 == 0 } (1..10);
# (2, 4, 6, 8, 10)open(FH, mode, file)打开文件并关联到文件句柄。
Parameters
| Name | Type | Description |
|---|---|---|
| filehandle | FH | 文件句柄 |
| mode | string | 打开模式如 '<','>','>>' |
| filename | string | 文件名 |
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
| Name | Type | Description |
|---|---|---|
| expr | scalar | 待检测值 |
Returns
布尔,已定义返回真
Example
perl
my $x;
print defined($x) ? "yes" : "no"; # no
$x = 0;
print defined($x) ? "yes" : "no"; # yes