Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Greate Monks,

I have Arrays, Hash and scalar. I should find the word "tiger" in all the arrays, hash, scalar.

Please suggest me in short way

I tried:

@array_1 = ("cat", "rat", "lion"); @array_2 =("dog", "tiger"); $variable="horse"; %hash=("1" => 'peacock', "2" => 'duck') ; foreach (@array_1) { if ($_ eq "tiger") { print "\nfound $_"; } } foreach (@array_2) { if ($_ eq "tiger") { print "\nfound $_"; } }

etc ...

I think its too long.

Replies are listed 'Best First'.
Re: Find the word in Array, Hash, Scalar
by gopalr (Priest) on May 11, 2005 at 09:03 UTC

    Hello

    Everything in foreach

    @array_1 = ("cat", "rat", "lion"); @array_2 =("dog", "tiger"); $variable="horse"; %hash=("1" => 'peacock', "2" => 'duck') ; foreach (@array_1, @array_2, $variable, @hash{keys %hash}) { if ($_ eq "tiger") { print "\nfound $_"; } }

    Thanks

    Gopal.R

      @hash{keys %hash} really is a bad idea...

      What will this do? it will create a list of all the keys in the hash, use that list in a hash slice and return all values.

      If you want to get all values of a hash then there is the values function... it is shorter, cleaner and more efficient.

      (Another possibilty would ofcourse be to use kapproach's approach, which is probably better)

      Or, to expand on the parent poster's suggestion, stuff it all in a big array and then grep on it.

      Remember rule one...

Re: Find the word in Array, Hash, Scalar
by astroboy (Chaplain) on May 11, 2005 at 10:48 UTC
    Have a look at Quantum::Superpositions:
    use Quantum::Superpositions; my @array =("dog", "tiger"); my %hash=("1" => 'peacock', "2" => 'duck'); my $scalar = "horse"; my $search_element = "tiger"; print "found!" if ($search_element eq any(@array, $scalar, (values %ha +sh)));
Re: Find the word in Array, Hash, Scalar
by Roy Johnson (Monsignor) on May 11, 2005 at 11:50 UTC
    print "\nfound $_\n" if grep {$_ eq 'tiger'} (@array_1, @array_2, $variable, values %hash)

    Caution: Contents may have been coded under pressure.
Re: Find the word in Array, Hash, Scalar
by kprasanna_79 (Hermit) on May 11, 2005 at 09:26 UTC
    Hai,
    I tried in these combination and got answer. They are
    1 Way..
    @array1 = ("cat","rat","lion"); @array2 = ("dog","tiger"); $variable = "tiger"; %hash= ("tiger" => 'peacock', "2" => 'tiger'); map{print $_."\n" if($_ eq 'tiger')}(@array1,@array2,$variable,%hash);

    2 Way..
    @array1 = ("cat","rat","lion"); @array2 = ("dog","tiger"); $variable = "horse"; %hash= ("1" => 'peacock', "2" => 'duck') ; map{print $_ if($_ eq 'tiger')}(@array1,@array2,$variable,%hash);

    3 Way..
    @array1 = ("cat","rat","lion"); @array2 = ("dog","tiger"); $variable = "tiger"; %hash= ("1" => 'peacock', "2" => 'tiger'); map{print $_."\n" if($_ eq 'tiger')}(@array1,@array2,$variable,%hash);
    --Prasanna.k