Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: find a string in an array of arrays

by Tanktalus (Canon)
on Feb 06, 2008 at 22:01 UTC ( [id://666684]=note: print w/replies, xml ) Need Help??


in reply to find a string in an array of arrays

ITYM:

my ($grepresult) = grep { $_->[0] eq $SearchStr } @cdata
Or you could have $_->[0] =~ $SearchStr - but then your dot would match any character, which is probably not what you intended.

Update: Added parens as per lodin's comment, as if I hadn't bitten myself twice already today with that oversight ;-)

Replies are listed 'Best First'.
Re^2: find a string in an array of arrays
by lodin (Hermit) on Feb 06, 2008 at 23:20 UTC

    Beware of grep in scalar context. You need to use parentheses to create list context.

    Nowadays, i.e. with Perl 5.10, you don't have to specify how to match in the grep. Using the ~~ operator you can let $SearchStr handle that.

    my $SearchStr = 'foo.txt'; #my $SearchStr = qr/^foo_.*\.txt\z/i; #my $SearchStr = [ 'foo.txt', 'bar.txt' ]; my ($grepresult) = grep { $_->[0] ~~ $SearchStr } @cdata;

    lodin

Re^2: find a string in an array of arrays
by johngg (Canon) on Feb 06, 2008 at 23:02 UTC
    but then your dot would match any character

    You could do \Q...\E to quote the metacharacter.

    my ( $grepresult ) = grep { $_->[0] =~ m{\Q$SearchStr\E} } @cdata;

    Cheers,

    JohnGG

    Update: I also missed the scalar/list problem, parentheses added. lodin ++

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://666684]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-25 10:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found