如何将已被推入数组的哈希独立于“源”哈希?
my %country; my Hash @array; %country{ 'country' } = 'France'; @array.push(%country); %country{ 'country' } = 'Germany'; @array.push(%country); .say for @array;
输出是:
{country => Germany} {country => Germany}
当然,这不是我想要的.
解决方法
当您将哈希%国家/地区推送到阵列时,您将推送对%country的引用.这样,每个数组元素都将引用相同的原始哈希%国家/地区.当您更改散列值时,所有数组元素都将反映此更改(因为它们都引用相同的散列).如果要在每次推送时创建新哈希,可以尝试使用匿名哈希来代替.例如:
%country{ 'country' } = 'France'; @array.push({%country}); %country{ 'country' } = 'Germany'; @array.push({%country});
通过这种方式,每次都会推送对%country副本的引用(而不是对%country的引用).
输出:
{country => France} {country => Germany}