Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl : creating array of known size


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.

like image 560
eouti Avatar asked Dec 03 '22 08:12

eouti


2 Answers

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";
}
like image 149
Alex Avatar answered Dec 22 '22 02:12

Alex


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.

like image 37
Nathan Fellman Avatar answered Dec 22 '22 03:12

Nathan Fellman