设计一个函数,根据调用上下文返回不同类型结果并给出单元测试

解读

国内 Perl 岗位集中在运维自动化、日志清洗、金融对账、生物信息脚本等场景。面试官出此题,核心想验证三点:

  1. 是否真正理解 Perl 的“上下文”机制(scalar / list / void);
  2. 能否写出既安全又符合业务直觉的返回值;
  3. 单元测试能否覆盖主流测试框架(Test::More),并体现中国开发者对“边界、异常、性能”的严谨习惯。

题目虽短,却能把“语法、工程、测试”串起来,是区分“脚本小子”与“工程型 Perl 程序员”的试金石。

知识点

  1. wantarray 与 defined wantarray:判断调用上下文。
  2. 多态返回:list 上下文返回列表,scalar 上下文返回单一值,void 上下文可做副作用。
  3. 引用与复用:返回数组引用可避免大列表拷贝,符合国内大数据日志场景。
  4. 单元测试:use Test::More; 计划测试数量;ok/is/deep_ok 组合;子测试 subtest 隔离场景。
  5. 中国工程规范:异常用 croak;中文字符串用 utf8::all;日志打印到 STDOUT 便于阿里/腾讯日志服务采集。

答案

package Utils::LogParser;
use strict;
use warnings;
use utf8;
use Carp qw(croak);
use Exporter 'import';
our @EXPORT_OK = qw(parse_access_log);

# 解析 Nginx 访问日志
# 上下文行为:
#   list  -> 返回所有状态码列表
#   scalar-> 返回 200 状态码计数
#   void  -> 直接打印统计报表到 STDOUT(方便日志服务采集)
sub parse_access_log {
    my ($log_path) = @_;
    croak "日志文件不能为空" unless defined $log_path && -f $log_path;

    open my $fh, '<:encoding(UTF-8)', $log_path
      or croak "无法打开 $log_path: $!";

    my @codes;
    while (my $line = <$fh>) {
        # 国内常用组合日志格式:... "GET /index.html HTTP/1.1" 200 1234
        my ($code) = $line =~ m/\s(\d{3})\s\d+$/;
        push @codes, $code if defined $code;
    }
    close $fh;

    # 上下文分支
    if (defined wantarray) {
        return wantarray ? @codes : scalar grep { $_ eq '200' } @codes;
    } else {
        # void 上下文:直接输出报表
        my %hist;
        $hist{$_}++ for @codes;
        print "=== 状态码统计 ===\n";
        printf "%s\t%d\n", $_, $hist{$_} for sort keys %hist;
    }
    return;
}

1;

单元测试(t/01_context.t):

use strict;
use warnings;
use utf8;
use Test::More tests => 6;
use Utils::LogParser qw(parse_access_log);
use File::Temp qw(tempfile);

# 准备临时日志
my ($fh, $filename) = tempfile(UNLINK => 1);
print $fh <<'LOG';
127.0.0.1 - - [01/Jun/2025:10:10:10 +0800] "GET /api/user HTTP/1.1" 200 512
127.0.0.1 - - [01/Jun/2025:10:10:11 +0800] "POST /api/login HTTP/1.1" 500 0
127.0.0.1 - - [01/Jun/2025:10:10:12 +0800] "GET /index.html HTTP/1.1" 200 1024
LOG
close $fh;

# 1. list 上下文
my @codes = parse_access_log($filename);
is_deeply \@codes, [200, 500, 200], 'list 上下文返回全部状态码';

# 2. scalar 上下文
my $count = parse_access_log($filename);
is $count, 2, 'scalar 上下文返回 200 出现次数';

# 3. void 上下文
my $output;
{
    open my $oldout, '>&', \*STDOUT or die "dup: $!";
    close STDOUT;
    open STDOUT, '>', \$output or die "redirect: $!";
    parse_access_log($filename);
    close STDOUT;
    open STDOUT, '>&', $oldout or die "restore: $!";
}
like $output, qr/200\s+2/, 'void 上下文报表包含 200 计数';
like $output, qr/500\s+1/, 'void 上下文报表包含 500 计数';

# 4. 异常测试
eval { parse_access_log('/tmp/not_exist.log') };
like $@, qr/无法打开/, '异常文件触发 croak';

# 5. 空文件
($fh, $filename) = tempfile(UNLINK => 1);
close $fh;
is parse_access_log($filename), 0, '空文件 scalar 上下文返回 0';

运行:

$ prove -lv t/01_context.t

国内 CI(如阿里云效、腾讯蓝盾)可直接采集 TAP 输出,无需额外插件。

拓展思考

  1. 大日志性能:若文件超过 2 GB,可改用 Tie::File 或 IO::Uncompress::Gunzip 流式读取,避免一次性加载。
  2. 上下文语义扩展:支持“哈希引用”上下文,调用者传入 { want_hash => 1 },函数返回按状态码分组的数组引用,兼顾灵活与效率。
  3. 中文日志乱码:国内常见 GB18030 编码,需用 Encode::Guess 自动检测,防止“?” 乱码导致正则匹配失败。
  4. 测试分层:在大型金融对账系统,可再用 Test::MockModule 模拟磁盘 IO,实现毫秒级单元测试,满足深圳、上海两地每日千万级对账时效要求。
  5. 文档与交付:按中国银行业 Perl 编码规范,函数上方必须包含 POD,给出中文示例,方便外包团队二次开发。