http://qs1969.pair.com?node_id=193468


in reply to Re: best data structure
in thread best data structure

grep will work for this, but it's not a good solution to check for an existing item, especially not via regexp, because it will always iterate over the whole list, even if the elemet is fond at the first position.

So first thought would be a hash again, withe code like that:

our @array = 'a' .. 'e'; our @figure_out = 'd' .. 'g'; { my $index = 0; my %h = map {$_=>$index++} @array; while( my($k,$v) = each %h ){ my $n = shift @figure_out or next; $h{$n} = $index++ unless exists $h{$n}; } @array = sort {$h{$a}<=>$h{$b}} keys %h; }

That may work in special cases, but `perldoc -f each` tells us not to change a hash while iterating over it, so we end up doing it like that:

{ my @new = (); my $in = sub { for(@array,@new){ return 1 if $_ eq $_[0] } return 0 }; local $_; while( @array ){ $_ = shift @array; #this is of course pseufo for really figuring out # a new value my $new = shift @figure_out or next; $in->($new) or push @array,$new; } continue { push @new,$_ } @array = @new; }

An that works.

--
http://fruiture.de