Howto access an array that is in a hash
Say you have a hash element that contains an array and you want to loop through the array set. You usually have these types of data sets when you are trying to gather data.
example:
We will use the following code to build the hash:
#!/usr/bin/perl
use Data::Dumper;
my %data_set;
$data_set{'users'} = ();
$data_set{'users'}[0] = "testA";
$data_set{'users'}[1] = "testB";
$data_set{'users'}[2] = "testC";
$data_set{'users'}[3] = "testD";
$data_set{'users'}[4] = "testE";
$data_set{'users'}[5] = "testF";
print Dumper(%data_set);
Output:
$VAR1 = 'users';
$VAR2 = [
'testA',
'testB',
'testC',
'testD'
];
Now that we know the hash element is populated we want to access each array element. This can be done with making some crazy counter in a while loop. Check it out.
foreach my $user (@{$data_set{'users'}}){
print $user,"\n";
}
Now knowing you can access a array with in a hash using @{
Here is the same script above but using push:
#!/usr/bin/perl
use Data::Dumper;
my %data_set;
$data_set{'users'} = ();
push(@{$data_set{'users'}},"testA");
push(@{$data_set{'users'}},"testB");
push(@{$data_set{'users'}},"testC");
push(@{$data_set{'users'}},"testD");
foreach my $user (@{$data_set{'users'}}){
print $user,"\n";
}