1

我正在学习参考资料。在 Intermediate Perl (2nd edition) : CHAPTER 5 (References and Scoping) 一书中,给出了以下代码:

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]#工作过

${$ref}[2]#工作过

所以,

书上给出的代码错了吗?(有人告诉我这是一本好书 - 我正在阅读它,我觉得它很棒。不确定这是印刷错误还是我做错了什么)

4

1 回答 1

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−&gt;[2]\n"; # prints jacket\n
}
print "$ref−&gt;[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
于 2013-08-03T12:45:56.387 回答