返回值
就如其他Perl表达式,调用子程序也会在不同上下文中有不同的行为。你可以使用函数(也可以叫做wantlist)来检测子程序处于什么上下文当中,并返回一个合适的结果到上下文:
- sub contextualSubroutine {
- # Caller wants a list. Return a list
- return ("Everest", "K2", "Etna") if wantarray;
- # Caller wants a scalar. Return a scalar
- return 3;
- }
- my @array = contextualSubroutine();
- print @array; # "EverestK2Etna"
- my $scalar = contextualSubroutine();
- print $scalar; # "3"