簡體   English   中英

不重置時,為什么我的價值會改變?

[英]Why does my value change when I am not resetting it?

以下示例展示了我正在努力解決的問題。 在玩具示例中,我有一個具有兩個級別的數組@actors 我也有一系列的哈希值@people ,它們用於“查找” @actors人員的@actors

該程序的輸出應為:

blue, blue     cat, cat
red, red     dog, dog
blue, blue     cat, cat
red, red     dog, dog

但是相反,我得到了:

blue, cat     cat, cat
red, dog     dog, dog
blue, cat     cat, cat
red, dog     dog, dog

也就是說,似乎在設置$favanim[$i][$j]我似乎也覆蓋了$favcols[$i][$j] 我懷疑出於某種原因, @actors是二維數組這一事實意味着,通過=進行賦值是作為引用而不是作為值,盡管我不知道為什么或如何停止它。 請幫忙!

玩具程序在這里:(我很抱歉,如果可以簡化它,但仍然表現出問題-我花了整個下午的大部分時間將其簡化為這個問題)

#!/usr/bin/perl -w

my @people = ();
$people[0]{'alternative full names for regexp'} = 'matthew smith|matt smith';
$people[1]{'alternative full names for regexp'} = 'david tennant|dave tennant';
$people[0]{'fav colour'} = 'red';
$people[1]{'fav colour'} = 'blue';
$people[0]{'fav animal'} = 'dog';
$people[1]{'fav animal'} = 'cat';

my @actors = ();
$actors[0][0] = 'David Tennant';
$actors[0][1] = 'Matt Smith';
$actors[1][0] = 'David Tennant';
$actors[1][1] = 'Matt Smith';
my @favcols = @actors;
my @favanim = @actors;

for ($i=0; $i<2; $i++) {
  for ($j=0; $j<2; $j++) {
    my @matching_people = grep{$actors[$i][$j] =~ m/^$_->{'alternative full names for regexp'}$/i} @people;
    $favcols[$i][$j] = $matching_people[0]{'fav colour'};
    $favanim[$i][$j] = $matching_people[0]{'fav animal'};
    print "$matching_people[0]{'fav colour'}, $favcols[$i][$j]     $matching_people[0]{'fav animal'}, $favanim[$i][$j]\n";
  }
}

嘗試使用

@favcols = map { [@$_] } @actors;
@favanim = map { [@$_] } @actors;

深層副本與淺層副本。

問題是您通過復制@favanim的內容來初始化@favcols@people ,其中包含兩個數組引用

$favcol[0]$favanim[0]設置為對同一數組[ 'David Tennant', 'Matt Smith' ]的引用,因此,當您修改$favcols[$i][$j]然后是$favanim[$i][$j]您正在覆蓋同一數組元素

我完全沒有理由初始化您的數組,如果您將它們聲明為

my (@favcols, @favanim);

然后您會發現您的程序符合您的期望

順便說一句,您必須始終 use strict ,並且在命令行上use warnings優於-w

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM