开发者

push an array of references to any number of hashes [ perl ]

suppose i have an array:

@array = {
'A'    =>    "",
'B'    =>    0,
'C'    =>    0,
'D'    =>    0,
};

i can add an element by:

$count = 0;
$array[$count]->{A} = 开发者_StackOverflow中文版"abcd";
$array[$count]->{B} = 789;
$array[$count]->{C} = 456;
$array[$count]->{D} = 123;

and another element,

$count++;
$array[$count]->{A} = "efgh";
$array[$count]->{B} = 111;
$array[$count]->{C} = 222;
$array[$count]->{D} = 333;

how can i add elements to @array using push?


That first structure you have is a hash reference, not an array. You cannot add values to a Hash via push. push will only operate on an array. If you wish to add a value to a hash reference you will need to either use -> notation or dereference.

$hash->{ 'key' } = $val;  // ->
%{ $hash }{ 'key' } = $val;  //dereferencing

If you have an array reference inside of a hash reference you can access it in the same manner as above.

$hash->{ 'array key' }->[$index] = $val;
@{ $hash->{ 'array key' }}[$index] = $val;

As for creating an array you use ( and ) like so

my @array = ( "One", "Two", "Three" );

Another option is to use the qw() shortcut like so

my @array = qw(one two three);

Additionally you can create an array by reference using [ and ]

my $array_ref = [ 1, 2, 3 ];

Finally to push a value to an array you use push

push(@array, $value);

Though, push being a list context function can be written sans parens.

push @array, $value;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜