Perl数组包含它自己



我不明白这小段代码是怎么回事。

我已经把关于它的输出和评论放在中间,在产生它的打印语句之后

my @regions = (
0,
1,
2,
[ 0, new Point(3,1), new Point(3,2), new Point(3,3) ],
4,
5 );
$reg1 = 3;
print "1: $regions[$reg1] n";
@reg1 = @{regions[$reg1]};
print "2: $reg1[0]n";
print "3: $reg1[0][1]n";
print "4: ", Point::stringPoint($reg1[0][1]), "n";
# HERE IS THE OUTPUT from the above print statements, with comments about my confusion appended
1: ARRAY(0xe8b0e0)      # ok - element 3 of @regions is an array, as expected.
2: ARRAY(0xe8b0e0)      # It appears to be an array of one element, which is itself. ???
3: Point=HASH(0xfda5e0) # We have go 'down' one more level to get what we want - that makes no sense
4: 3,1                  # Yes, there it is
package Point;
sub new {
my $class = shift;
my $self = {
x => shift,
y => shift
};
bless $self, $class;
return $self;
}
sub stringPoint
{
my $p = shift;
return "$p->{x},$p->{y}";
}
" Code related to new question (with output) " ;

我真正的问题是:
如何直接方便地使用另一个数组中的数组(而不是它的副本(
唯一的方法是(总是(取消引用引用吗
例如下面的两个不起作用的例子。

以下是我尝试过的:

my $ref1 = @{$regions[3]};
@{$ref1}[2] = new Point(4, 5);  # changes original array
print1Region(3, $ref1);
# OUTPUT = (3,1) (4,5) (3,3)
my @arr1 = @{$ref1};
$arr1[1] = new Point(2,6);  # does not
print1Region(3, $ref1);
# OUTPUT = (3,1) (4,5) (3,3)
$ref1[0] = new Point(1,4);  # does not
print1Region(3, $ref1);
# OUTPUT = (3,1) (4,5) (3,3)

@{regions[$reg1]}是一种奇怪且未记录的@regions[$reg1]编写方式。(这是一种用于双引号字符串文字的语法文档。(

@regions[$reg1]是一个只有一个元素的数组切片,这是一种奇怪的$regions[$reg1]写入方式。

因此,您并没有得到$regions[$reg1]引用的数组的第一个元素;您只是得到了@regions的第一个元素。


让我们看看

my $ref1 = @{$regions[3]};
@{$ref1}[2] = new Point(4, 5);

问题#1

@"取消",因此

my $ref1 = @{$regions[3]};

只是编写的一种复杂方式

my $ref1 = $regions[3];

(好吧,这不太正确,因为前者会自动激活,但这与这里无关。(

问题#2

再次使用一个元素的数组切片。务必使用use strict; use warnings;并注意警告!

@{$ref1}[2] = new Point(4, 5);

应该是

${$ref1}[2] = new Point(4, 5);

使用"箭头符号"写得更干净。

$ref1->[2] = new Point(4, 5);

问题#3

最后,不要使用间接方法调用。它们会引发问题。

$ref1->[2] = new Point(4, 5);

应该是

$ref1->[2] = Point->new(4, 5);

结论

my $ref1 = @{$regions[3]};
@{$ref1}[2] = new Point(4, 5);

应该写成

my $ref1 = $regions[3];
$ref1->[2] = Point->new(4, 5);

如果没有变量,这将是

$regions[3]->[2] = Point->new(4, 5);

或者只是

$regions[3][2] = Point->new(4, 5);

相关内容

最新更新