On 22/08/2011 12:03, AKINLEYE wrote:
Hi anant

On Mon, Aug 22, 2011 at 8:42 AM, timothy adigun<2teezp...@gmail.com>  wrote:

Hi Anant,

I want to search whether a scalar '$a' contains any one of value of an
array
'@arr'.
How it may be done?
as its not correct : print "found" if $a =~ /@arr/;

#!/usr/bin/perl
use strict;
use warnings;

  my @arr=qw(fry ring apple law);
  print "Enter the string you are searching for:";
  chomp(my $search=<STDIN>); # you may have to check, if input is not string

  grep {print "found: $_" if/\b$search\b/}@arr;

  #grep compare your search with each array element
  # using $_ and then print out if item is found.
  # To make it plain you can ALSO use a foreach loop instead of grep,
  # iterate over your array element, comparing them each element
  # with your search item.

  foreach my $found(@arr){
   if($found=~/$/){
     print "found: ",$found,"\n";
   }
  }


Just a modification of the above idea this can be solved is . Still curious
how the above works though

You have misquoted it, so it doesn't work as it stands. The line

  if($found=~/$/){

should read

  if ($found =~ /$search/) {

Even so, it finds elements elements of @arr that contain $search as a
substring, whereas what is probably wanted is simply

  if ($found eq $search) {

#!/usr/bin/perl
use strict;
use warnings;

  my @arr=qw(fry ring apple law);
  print "Enter the string you are searching for:";
  chomp(my $search=<STDIN>); # you may have to check, if input is not string

I don't understand your comment. The input from stdin has to be a
string - it cannot be anything else.

   my (index) =  grep { arr[$_]  eq  $search }0..$#arr ;
    if( defined (index))
    {
       print " found" ;
     }

This code will not compile. It should read

  my ($index) =  grep { $arr[$_]  eq  $search } 0..$#arr ;
  if (defined ($index)) {
    print " found at $index" ;
  }

Rob

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to