in reply to Re: Is there an InString-like function?
in thread Is there an InString-like function?

To help your confusion, any maybe somebody else's...
Take SQL for example:
select name from phone_book where last_name in ("Smith","Jones","Schmidtz")
Hope this helps..

_14k4 - perlmonks@poorheart.com (www.poorheart.com)

Replies are listed 'Best First'.
Re: Re: Re: Is there an InString-like function?
by wiz (Scribe) on Jul 23, 2001 at 21:01 UTC
    In this case, there is a very easy way of doing this.
    Now all you really have to do it go if ($var =~ /^[12345]/).
    Now if you wanted to do a search through strings, i would suggest going,  if ($var =~ /^[qw(Smith Jones Schmidtz)]/).
    I tested both scripts on Win2k and Active Perl 5.6.1. So basically it works to  if ($variable =~ /^##data to search through here##/). this means if $variable finds that any of the search variables are true (if you don't use ^ then it does an and/or search), it does it's required task.


    Update:
    With help from many people, when doing a string search, drop the [] from a string search, or else your searching through the characters of the string.
    ----------------------------
    Wiz, The VooDoo Doll
    Head Master of 12:30 Productions
    ----------------------------
      Wiz,

      I tried your code and I am either missing something or it does not work as advertised. See my following code...

      my @foo = qw(JohnSmith Smiccky aaaaaa); foreach my $f (@foo) { print "Yep $f \n" if ($f =~ /^[qw(Smith Jones)]/); }
      The result I get is ..
      Yep JohnSmith Yep Smiccky
      Which is quite obviously not an "in" relationship. If I add a "JJJJJ" entry to the list, that one will match as well. So it seems that you are still creating a set of individual characters, not something larger.
      =pod /^[adsf0asd]/ will match if $_ contains a or d or f or 0 or s . It matches character classes, not words. =cut my @matchthis = qw(abe age rod); my $beginswiththis = join '|', @matchthis; print "looking for strings that begin with '$beginswiththis'\n"; @_ = qw( abey AbEy abeoy agg aggb agge agee rodo rodd rddo); print "looking through:", join(' ', map { "'".$_."'" } @_),"\n"; for (@_) { print "Found one: ",$_,"\n" if(/^($beginswiththis)/); }

      As was already pointed out, this if ($var =~ /^[qw(Smith Jones Schmidtz)]/) doesn't work as it just creates a character class equivalent to [SmithJonescdz] - which just compares to the first character of $var. Two solutions:

      my @names = qw(Smith Jones Schmidtz); my $pattern = join '|', @names; if ($var =~ /^(?:$pattern)/) # or quicker if ($var =~ /^Smith/ || $var =~ /^Jones/ || $var =~ /^Schmidtz/)

      -- Hofmator

        so is /^(?:$pattern)/ faster than just /^($pattern)/