http://qs321.pair.com?node_id=617437

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

Fantasy monks,

Apologies If this has been discussed already,

# Program : 1 #!/usr/bin/perl use strict; my $match = 'A'; my @array = qq[Anthony Mark Alex A]; if ( grep( /^$match/,@array ) ) { print "Matched\n"; }
Output : Matched
# Program : 2 #!/usr/bin/perl use strict; my $match = 'A'; my @array = qq[Anthony Mark Alex A]; if ( grep( /$match$/,@array ) ) { print "Matched\n"; } <code> Output : Matched
# Program : 3 #!/usr/bin/perl use strict; my $match = 'A'; my @array = qq[Anthony Mark Alex A]; if ( grep( /^$match$/,@array ) ) { print "Matched\n"; }
What is the problem with the 3rd program ? am I missing something there ?

Replies are listed 'Best First'.
Re: perl's grep function with '^' and '$'
by shmem (Chancellor) on May 25, 2007 at 09:13 UTC
    Try:
    perl -le 'my @array = qq[Anthony Mark Alex A]; print for @array'

    See? What does the qq[] operator do? you want qw[].

    You would have spotted that had you written e.g.

    # Program : 2 #!/usr/bin/perl use strict; my $match = 'A'; my @array = qq[Anthony Mark Alex A]; if ( my @list = grep( /$match$/,@array ) ) { print "Matched: ".join(', ', map {"'$_'"} @list)."\n"; } __END__ Matched: 'Anthony Mark Alex A'

    learn to debug... ;-)

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: perl's grep function with '^' and '$'
by clinton (Priest) on May 25, 2007 at 09:13 UTC
    Indeed you are, you should be using qw not qq. See perlop

    # Program : 3 #!/usr/bin/perl use strict; my $match = 'A'; my @array = qw[Anthony Mark Alex A]; if ( grep( /^$match$/,@array ) ) { print "Matched\n"; }
Re: perl's grep function with '^' and '$'
by moritz (Cardinal) on May 25, 2007 at 09:16 UTC
    The problem is in the quoting. qq[...] quotes a string, so your array has just one element - that happens to start with an A.

    use qw(Anthony Mark Alex A) and all is fine.