Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

perl's grep function with '^' and '$'

by jesuashok (Curate)
on May 25, 2007 at 09:07 UTC ( #617437=perlquestion: print w/ replies, xml ) Need Help??
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 ?

Comment on perl's grep function with '^' and '$'
Select or Download Code
Re: perl's grep function with '^' and '$'
by shmem (Canon) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://617437]
Approved by clinton
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (12)
As of 2015-07-06 15:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (77 votes), past polls