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 ++