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

hi monks,

i am a little stumped. i thought the following code would assign to the variable "match" the value of the item in the array that the variable "term" matches, but i'm getting nada.

can anyone tell me why, or if i'm doing something wrong?
#!/usr/bin/perl use strict; use warnings; my @myTerms = ( 'foo bar', 'blah' ); my $term = "foo"; if ( grep /\Q$term\E/, @myTerms) { # the line that i'm having trouble with - $match always = null. my ($match) = ( grep $term =~ /\Q$_\E/, @myTerms ); print "$term does match with $match\n"; } # end-if exit;

cheers,
reagen

Replies are listed 'Best First'.
Re: regex to return matched value from array
by BrowserUk (Patriarch) on Sep 22, 2004 at 15:06 UTC
    use List::Util qw[ first ]; my @terms = ( 'foo bar', 'blah' ); my $term = 'foo'; my $match = first{ /\Q$term/ } @terms; print $match; foo bar

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
Re: regex to return matched value from array
by borisz (Canon) on Sep 22, 2004 at 15:06 UTC
    I think you should nit use grep for that. Right from your description: does this code meet your requirements?
    my @myTerms = ( 'foo bar', 'blah' ); my $term = "foo"; for ( @myTerms ) { print "$term match with $_\n" if /\Q$term\E/; }
    Boris
Re: regex to return matched value from array
by JediWizard (Deacon) on Sep 22, 2004 at 15:08 UTC

    I'm not sure why you are using $_ in the grep within the if block, but if you use $term as you did originally it will work.

    May the Force be with you
      ahh of course. thankyou.

      the problems with cut and paste...
Re: regex to return matched value from array
by zejames (Hermit) on Sep 22, 2004 at 15:14 UTC
    your code is not very fast, as you search for $term twice. The following code does what you want :

    #!/usr/bin/perl use strict; use warnings; my @myTerms = ( 'foo bar', 'blah' ); my $term = "foo"; my ($match) = ( grep /\Q$term\E/, @myTerms ); print "$term does match with $match\n" if ($match);

    Kind regards

    --
    zejames
Re: regex to return matched value from array
by pelagic (Priest) on Sep 22, 2004 at 15:09 UTC
    ... your  $_ is not set to anything!

    pelagic