in reply to Question with Dynamically Creating arrays.
Now i have encountered a problem.....They would have to manually edit the code to create an array called @aa to store its values.
If I understood this well enough, you will add the keys manually to the hash right?, you can do that directly without having to explicitly create an array every time to hold the values for you. That other array holding the key names can be dynamically updated for hash keys by simply assigning to the array the keys of the hash using the keys function...
UPDATE:This post is a response to the OP original post which did not bear a mention of the requirement that he presented in the response to kennethk reply to the same post.. It is possible however to integrate further approaches towards achieving the OP's desired goal, for example:#!/usr/local/bin/perl use strict; use warnings; my %hash; my @array_keys; my @keys = qw(xx yy zz); @hash{@keys}=([{'key1'=>1}],[{'key2'=>2}],[{'key3'=>3}]); #hash slice @array_keys = keys %hash; print "@array_keys\n"; push @{$hash{'aa'}},{'key4'=>4}; #add another key @array_keys = keys %hash; #update the array print "@array_keys\n";
The following code is still welcoming improvement...for (@array_keys){ for my $element ($hash{$_}){ my @val; for my $element1 ($element->[0]){ @val = values %$element1; } print "@val\n"; } } #OR @array_values = values %hash; for (@array_values){ for my $element ($_){ my @val; for my $element1 ($element->[0]){ @val = values %$element1; } print "@val\n"; } }
use strict; use warnings; use Data::Dumper; my %hash; my @array_values; my @keys = qw(xx yy zz); @hash{@keys}=([{'key1'=>'ipconfig'}],[{'key2'=>'dir'}]); @array_values = values %hash; my %hash_output; for (@array_values){ for my $element ($_){ for my $element1 ($element->[0]){ for my $result (values %$element1){ my $outcome = `$result`; push @{$hash_output{command}[0]}, $out +come; } } } } print Dumper(\%hash_output);
|
|---|