我还没有掌握数组和散列,散列数组,散列哈希等之间的区别,所以我不知道下面的代码定义了什么。有人会告诉我哪些是好的吗?
my $col_props = [
{ min_w => 50, # Minimum column width.
max_w => 50, # Maximum column width.
justify => 'left', # One of left|center|right ,
font => $pdf->corefont( "Arial", -encoding => "latin1" ),
},
{ min_w => 110, # Minimum column width.
max_w => 110, # Maximum column width.
justify => 'left', # One of left|center|right ,
font => $pdf->corefont( "Arial", -encoding => "latin1" ),
},
{ min_w => 110, # Minimum column width.
max_w => 110, # Maximum column width.
justify => 'left', # One of left|center|right ,
font => $pdf->corefont( "Arial", -encoding => "latin1" ),
},
];
但是,我真正的问题是,根据上面的代码,我如何动态填充$col_props
?
答案 0 :(得分:3)
$col_props
是哈希数组的引用。
例如,第二个条目的最大列宽为
$col_props->[1]{max_w}
如何填充它取决于您想要做什么。假设您在%column_data
中有一个列定义,那么您可以使用
push @$col_props, \%column_data
修改或添加其中一个哈希的字段只需分配给它,例如
$col_props->[2]{min_w} = 20
答案 1 :(得分:0)
$col_props
是一个哈希数组。
分配中的$
和[ ]
表明$col_props
是数组引用。
一种方法可能是这样的:
#!/usr/bin/perl -w
my $col_props = [
{ min_w => 50, # Minimum column width.
max_w => 50, # Maximum column width.
justify => 'left' # One of left|center|right ,
},
{ min_w => 110, # Minimum column width.
max_w => 110, # Maximum column width.
justify => 'left' # One of left|center|right ,
},
{ min_w => 110, # Minimum column width.
max_w => 110, # Maximum column width.
justify => 'left' # One of left|center|right ,
},
];
foreach my $ref (@{$col_props}) { #1 print
print "min_w: ". $ref->{min_w} . "\n"
. "max_w: " . $ref->{max_w} . "\n";
}
my %new_hash = ( # create a new hash to push
min_w => 1,
max_w => 2,
justify => 'right'
);
push @{$col_props}, \%new_hash; # pushing the new_hash reference
print "\n";
foreach my $ref (@{$col_props}) { #2 print
print "min_w: ". $ref->{min_w} . "\n"
. "max_w: " . $ref->{max_w} . "\n";
}
#1 print:
min_w: 50
max_w: 50
min_w: 110
max_w: 110
min_w: 110
max_w: 110
#2 print:
min_w: 50
max_w: 50
min_w: 110
max_w: 110
min_w: 110
max_w: 110
min_w: 1
max_w: 2
为了更好地理解,请查看here。