解除引用运算符 - >不工作

时间:2013-08-03 12:42:08

标签: perl reference

我正在学习参考资料。在中级Perl(第2版):第5章(参考和范围)中,给出了以下代码:

my $ref;
{
    my @skipper = qw(blue_shirt hat jacket preserver sunscreen); # ref count is 1
    $ref = \@skipper; # ref count is 2
    print "$ref−>[2]\n"; # prints jacket\n
}
print "$ref−>[2]\n"; # still prints jacket\n # ref count is 1

当我运行此代码时,它给出了输出:

ARRAY(0x83fc890)−>[2]

ARRAY(0x83fc890)−>[2]

以为应该打印夹克。

http://ideone.com/y8ZLsp

当我尝试在没有引号的情况下运行它时,我得到了输出:

Unrecognized character \xE2; marked by <-- HERE after print $ref<-- HERE near column 12 at prog.pl line 5.

http://ideone.com/V9GbUe

我尝试了一些:

$$ref[2] #Worked

${$ref}[2] #Worked

所以,

书中给出的代码是错误的吗? (我被告知这是一本好书 - 我正在读它,我发现它很棒。不确定这是印刷错误还是我做错了什么)

1 个答案:

答案 0 :(得分:7)

您使用的是减号"−"U+2212)。这与ASCII连字符"-"U+002D)不同。

让我们看看您的代码实际包含的内容:

use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper <<'END';
my $ref;
{
    my @skipper = qw(blue_shirt hat jacket preserver sunscreen); # ref count is 1
    $ref = \@skipper; # ref count is 2
    print "$ref−>[2]\n"; # prints jacket\n
}
print "$ref−>[2]\n"; # still prints jacket\n # ref count is 1
END

输出(换行符更改为实际换行符):

my \$ref;
{
    my \@skipper = qw(blue_shirt hat jacket preserver sunscreen); # ref count is 1
    \$ref = \\\@skipper; # ref count is 2
    print \"\$ref\342\210\222>[2]\\n\"; # prints jacket\\n
}
print \"\$ref\342\210\222>[2]\\n\"; # still prints jacket\\n # ref count is 1