eouti
eouti

Reputation: 5648

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.

Upvotes: 4

Views: 7007

Answers (3)

DavidO
DavidO

Reputation: 13942

A hash is a good data-type to use for "sparse arrays." It seems like you're describing just that; a sparse array -- one where most of the elements would be undefined. Perl would let you pre-size a standard array, but that's not what you need. You seem to need a hash, where it wouldn't matter if you have $array[2], and $array[23], but none between, for example. Using a native array, as soon as you create $array[23], all unused elements below 23 would spring into existence with 'undef' as their value.

With the hash, you would have $item{2}, and $item{23}. You could get a list of which items are being held in the hash using the keys() function.

Upvotes: 5

Nathan Fellman
Nathan Fellman

Reputation: 127428

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.

Upvotes: 5

Alex
Alex

Reputation: 5893

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";
}

Upvotes: 7

Related Questions