LPM: variable comparison not working
Rich Bowen
rbowen at rcbowen.com
Sat May 27 12:12:40 CDT 2000
Tom Braun wrote:
>
> Ok, I'm trying to do some simple input data checking on a script I'm
> writing. $book is a string entered from the keyboard. @books is a list of
> available books. Both are chomped, so no new lines should be present. I'm
> doing something like this:
>
> $valid = 0;
> foreach (@books) {
> if ($_ eq $book) {
> $valid = 1;
> last;
> }
> }
>
> This never matches, even when $book is a value in @books. In trying to
> figure out why, I added a print statement to it as shown:
>
> $valid = 0;
> foreach (@books) {
> if ($_ eq $book) {
> $valid = 1;
> last;
> }
> print "$valid-$book-$_-\n";
> }
>
> I get output like the following (I used dashes since none of the variables
> should have them):
>
> --galatians-galatians
> --galatians-ephesians
> --galatians-philippians
> ...
> 0-galatians-philemon-
>
> As if this is not interesting enough, I tried it on my Windows 95 box
> (running ActivePerl 5.6) and it worked fine (I'm writing and was testing it
> on Linux). However, my linux box gives the same results from both Perl
> 5.005 and Perl 5.6.
>
> Does anyone have any idea what is going on? I've been beating my head
> against this for a couple days and just am not seeing it. Thanks
If what you're trying to do is figure out if $string is contained in
@array, perhaps what you need to do is use a hash. (Yes, this is a
cop-out. I don't see what's wrong with your existing code, but it sure
looks like you have some extra \n's in there somewhere.)
chomp (@books, $book);
%contains = map {$_ => 1} @books;
print "It's in there!\n" if $contains{$book};
Rich
--
Director of Web Application Development - The Creative Group
http://www.cre8tivegroup.com/
Author - Apache Server Unleashed - http://apacheunleashed.com/
More information about the Lexington-pm
mailing list