我有一个结构如下,其中包含哈希的哈希数组。从散列中取消引用值时出现错误。
$VAR1 = \{
'2001' => {
'Arunachal Pradesh' => {
'CHANGLANG' => [
{
'wheat' => '2',
'cotton' => '',
'rice' => '1'
}
],
'SUBANSIRI UPPER' => [
{
'wheat' => '',
'cotton' => '1',
'rice' => '2'
}
],
},
'Andhra Pradesh' => {
'CHITTOOR' => [
{
'wheat' => '34',
'cotton' => '14',
'rice' => '27'
}
],
'VIZIANAGARAM' => [
{
'wheat' => '2',
'cotton' => '',
'rice' => '8'
}
],
}
}
};
我正在尝试取消引用单个值,以便我可以将这些值填充到 mysql 数据库中。但是我在取消对单个值本身的引用时收到错误“在连接 (.) 或字符串中使用未初始化的值 $state”。代码如下:
while (my ($key, $href) = each(%$stat) ) {
my $state = $stat->{$state_name}; #where the first value is the state name & the second value is the district
print "$state\n";
}
州名代码如下:
if ($line =~ m/^State:,(\w+\s\w+),/){
$state_name = $1;
$stat->{$year}->{$state_name} = {};
}
我可以通过任何其他方式获取单个值,或者我需要将其分配给另一个散列等等。谢谢。
最佳答案
要正确地遍历您的结构,您需要一个更像这样的循环:
while (my ($year, $year_ref) = each(%$stat) )
{
while (my ($state, $state_ref) = each(%$year_ref) )
{
print "year = $year, state = $state\n";
}
}
如果您想遍历整个结构以展平它,您可以在其下添加额外的循环级别。
例如,由于您的结构中有五层,而最后一层下方的层是一个数组引用:
while (my ($year, $year_ref) = each(%$stat) )
{
while (my ($state, $state_ref) = each(%$year_ref) )
{
while (my ($city, $city_ref) = each(%$state_ref) )
{
foreach my $prod_rec ( @$city_ref )
{
while (my ($prod, $qty) = each(%$prod_rec) )
{
print "year = $year, state = $state, city = $city, prod = $prod, qty = $qty\n";
}
}
}
}
}
(如果我猜错了,将$state
下的关卡命名为$city
,请见谅,纯属猜测。)
关于mysql - Perl取消引用散列散列数组中的单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20533724/