我正在重新審視我幾年前構建的 perl 應用程式。我必須重建一些。但是今天我被困住了。我在使用哈希時遇到了一些麻煩。我有這個回圈遍歷一些哈希的測驗腳本。我不明白的是,最后一個回圈第二次'pid1' => $VAR1->[1]{'deal'}{'pid1'}作為輸出給出。我期待一個帶有產品資料的散列。我究竟做錯了什么?
#!usr/bin/perl
use strict;
use warnings;
use Data::Dumper qw(Dumper);
my %stores;
push @{$stores{'store1'}}, 'pid1';
push @{$stores{'store1'}}, 'pid2';
push @{$stores{'store2'}}, 'pid1';
print Dumper(\%stores);
my %products = (
'pid1' => {
'name' => 'Product 1',
'color' => 'red'
},
'pid2' => {
'name' => 'Product 2',
'color' => 'blue'
}
);
print Dumper \%products;
my @offers;
foreach my $storeid (keys %stores) {
foreach my $pid (@{$stores{$storeid}}) {
my %offer;
$offer{$storeid}{'deal'}{$pid} = $products{$pid};
push(@offers, %offer);
}
}
print Dumper(\@offers);
$VAR1 = {
'store1' => [
'pid1',
'pid2'
],
'store2' => [
'pid1'
]
};
$VAR1 = {
'pid2' => {
'name' => 'Product 2',
'color' => 'blue'
},
'pid1' => {
'color' => 'red',
'name' => 'Product 1'
}
};
$VAR1 = [
'store1',
{
'deal' => {
'pid1' => {
'color' => 'red',
'name' => 'Product 1'
}
}
},
'store1',
{
'deal' => {
'pid2' => {
'name' => 'Product 2',
'color' => 'blue'
}
}
},
'store2',
{
'deal' => {
'pid1' => $VAR1->[1]{'deal'}{'pid1'}
}
}
];
uj5u.com熱心網友回復:
它的意思是
$VAR1->[1]{'deal'}{'pid1'} # $offers[1]{'deal'}{'pid1'}
和
$VAR1->[5]{'deal'}{'pid1'} # $offers[5]{'deal'}{'pid1'}
都是對同一個哈希的參考,看起來像
{
'color' => 'red',
'name' => 'Product 1'
}
如果您使用local $Data::Dumper::Purity = 1;生成可以實際執行的代碼,可能會更清楚。
$VAR1 = [
'store1',
{
'deal' => {
'pid1' => {
'color' => 'red',
'name' => 'Product 1'
}
}
},
'store1',
{
'deal' => {
'pid2' => {
'name' => 'Product 2',
'color' => 'blue'
}
}
},
'store2',
{
'deal' => {
'pid1' => {}
}
}
];
$VAR1->[5]{'deal'}{'pid1'} = $VAR1->[1]{'deal'}{'pid1'};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516895.html
標籤:perl哈希
