#!/usr/bin/perl
$a = "1234";
@b = reverse($a);
$c = reverse($a);
print @b,"\n"; #1234
print $c,"\n"; #4321
print reverse($a),"\n"; #1234
print scalar reverse($a),"\n"; #4321
print reverse($a)."\n"; #4321
首先我们要明确两个函数print和reverse的在perl中的定义(以下是perldoc中的解释)
print FILEHANDLE LIST
print LIST
Because print takes a LIST, anything in the LIST is evaluated in list context.
——————————————————————————————————
reverse LIST
In list context, returns a list value consisting of the elementsof LIST in the opposite order. In scalar context, concatenates theelements of LIST and returns a string value with all charactersin the opposite order.
从以上可以看出,print reverse(1234);其实是print LIST,那么reverse的参数也会被当作一个list,即只有一个元素的列表(1234),那么反转后还是1234。
如果想将结果反转成4321,就必须转成标量上下文,如上面程序中scalar ,或者用.连接一个字符串。