in reply to Efficient access to sparse lists?
for(my $x = 0; $x <= $#array; $x++) { next unless $array[$x]; # do stuff with $x and $array[$x] }
But that is obviously inefficient, especially if your list is VERY sparse. Like with elements numbered 100, 435, 1040, etc.
Why not use a hash? You can convert a sparse list to a hash like so:
my %hash = map { $x => $y } grep { my $y = $list[$x]; $y ne $undef; [$x, $y] } for(my $x = 0; $x <= $#list; $x++);
And use it like this:
$list{100} = 'dog'; $list{435} = 'cat'; $list{1040} = 'tax form'; while(($index, $element) = each %list) { # do stuff with $index and $element }
Other alternatives include using a pseudohash, or writing a tied array implementation that acts like a list in your code but works like a hash behind the scenes.
Good luck!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(corrections) Re: Answer: Efficient access to sparse lists?
by mwp (Hermit) on Jan 25, 2001 at 16:57 UTC | |
by Improv (Pilgrim) on Jan 26, 2001 at 01:45 UTC | |
by tye (Sage) on Jan 26, 2001 at 02:22 UTC | |
by BoredByPolitics (Scribe) on Jan 26, 2001 at 06:08 UTC | |
by tilly (Archbishop) on Jan 26, 2001 at 06:56 UTC | |
by tye (Sage) on Jan 30, 2001 at 21:11 UTC | |
by tilly (Archbishop) on Jan 30, 2001 at 21:30 UTC | |
|