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


in reply to best data structure

I'm not sure if it's exactly what you were looking for, but I used the built-in perl function grep to examine my list for entries that are already in there. Here's the snippet of code I used to test the grep function:
# Create an initial list @list = (9,2,3,4,5,6); # Data we wish to insert @insert_data = 4..9; # For every datum that we wish to # insert, check for it's existance # in the list and append it if it is # not found foreach $item (@insert_data){ next if grep /$item/, @list; push @list, $item; } # Print out our final list foreach $item (@list){ print $item, ","; }

This results in the output: 9,2,3,4,5,6,7,8.

Hope this helps -- Rolly

Update: See comments below for reasons why this isn't an efficient solution.

Replies are listed 'Best First'.
Re: Re: best data structure
by fruiture (Curate) on Aug 28, 2002 at 14:29 UTC

    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:

    --
    http://fruiture.de
Re: Re: best data structure
by rob_au (Abbot) on Aug 28, 2002 at 13:58 UTC
    While this too is an option to solve the problem at hand, you will find that over time and with larger sets of data, that this method will prove to be substantially slower. This is due to the fact that a grep or loop over all set elements will, in a worst-case scenario, occur with O(n) execution - In contrast, a hash-lookup operates with O(1) execution.

    As such this approach, particularly with larger data sets, can be justified, trading memory space for execution speed.