Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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

by jesuashok (Curate)
on May 25, 2007 at 09:07 UTC ( [id://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 ?

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-04-24 03:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found