I have to store data from request runned with Parallel::ForkManager.
But it comes not in order, I mean, I poll all ports of a switch, but some of them answer faster than others. So, I don't know how to save it, to display it later.
Can I do like that ?
my @array = ();
$array[10] = "i am a string corresponding to port 10"
$array[2] = "the one for the port 2"
...
print @array;
Or should I use a %hash with number of port as keys, but it seems not the best.
Thank you.
You can do this:
my @array = ();
$array[10] = "i am a string corresponding to port 10"
$array[2] = "the one for the port 2"
print @array;
But if some ports do not respond you will have undef entries in the slots of the array that were not filled. As you say, using a hash would be cleaner:
my %hash;
$hash{10} = "I am port 10";
$hash{2} = "I am port 2";
foreach my $key (keys %hash) {
print "$key: $hash{$key}\n";
}
In Perl you don't have to worry about the sizes of arrays. They grow as needed:
my @array; # defines an empty array
$array[0] = 4; # array has one element
$array[9] = 20; # array has 10 elements now
print join "-", @array;
# prints: 4--------20 because the empty places are undef
If you have many ports and are worried about having too many empty entries, use a hash. I can't see any reason not to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With