in reply to Testing for a string value within an array

What's wrong with making your very own exists function? It is quick, readable and configurable:

I would write it like this:

$filename = "$directory/$entry"; if( myExists( $filename, @mounts ) == 0 ){ push(@mounts, $filename); } sub myExists(){ my $compare = shift; foreach my $element (@_){ if( $element eq $compare ){ return 1; } } return 0; }

I know that this is more code than some of the previous solutions, but it has advantages. It is more readable and can allow you to more precisely define what it means to exist. Say for instance that you wanted to only add it if it were unique in the first 256 charachters, or alter it otherwise, this would be easy to do. In addition, it is also more resource friendly and less confusing than maintaining both arrays and hashes.

Good luck

Replies are listed 'Best First'.
Re^2: Testing for a string value within an array
by Roy Johnson (Monsignor) on May 03, 2005 at 23:58 UTC
    The problem is that you have to search the whole array every time you insert, making insertion an O(N) operation. With a hash, the lookup is essentially constant-time. Building an array becomes O(N^2), like bubblesort (which is also easy to read an understand, and which nobody uses).

    You can use a hash in all the same ways of defining existence. If you only want unique in the first 256 chars, only hash those.


    Caution: Contents may have been coded under pressure.
Re^2: Testing for a string value within an array
by Fletch (Bishop) on May 04, 2005 at 00:02 UTC

    It also does a full linear search of the entire list of items (which has to be copied onto the stack for each myExists call) if the element isn't already present. Replacing an O(N)-ish exists $seen{$key} with something exponential doesn't sound like it's worth any supposed simplification.

    Not wanting to use a hash for keeping track of set membership in Perl is in the same vein as people who want to do iterative-task-foo without using foreach or map. Learning the idioms will make your life much easier.