in reply to macthing a word a in array of words

Simple program that builds the array and checks for dupes.

#!/usr/bin/perl -w use strict; my @words; my $tries=0; while($tries!=2){ print "enter a new word:"; my $word=<STDIN>; chomp $word; if (grep{/$word/}@words) { print "$word already exists!\n"; $tries++; } else { push @words, $word; $tries=0; } } print "2 tries to enter a new word are up!\n"; print "Unique Words were:@words\n";
Using indicies is usually not the best way in Perl to search an entire array - there are better iterators. Of course many improvements could be made to the above code. List::More::Util has a first() routine that will be faster than my grep, but that is a speed thing not an algorithm thing.

Replies are listed 'Best First'.
Re^2: macthing a word a in array of words
by zarlag (Initiate) on Apr 03, 2011 at 13:57 UTC
    nice almost what i was looking for but thier seems to be a bug or it just how grep compares the words. $word doesnt exist on a letter or a of a $word exist. if you type in:noo than type in: oo it will say 'oo' exist. thanks for the replie. i try many more things and see what i can do. Thank you for the help YALL.
      yes, the regex could be better. When dealing with user input, you should allow whitespace before and after the input. Some common idioms:
      s/^\s+//; #remove leading whitespace s/\s+$//; #remove trailing whitespace
      Now that whitespace is not a factor, for the match then anchor the search term to front and rear. /^dog$/; matches dog but not doggie let me know how you get along with those hints.