4


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.

3 Answers 3

7

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";
}
Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

It prints "4 20", but with more spaces as SE won't print a run of those.
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.