in reply to Tyring to grep array of hashes

Hi dirtdog,

In addition to kennethk's solution of your problem, a few points on the grep:

Updated: Updated text of last bullet point slightly, as per Athanasius's reply.

Hope this helps,
-- Hauke D

Replies are listed 'Best First'.
Re^2: Trying to grep array of hashes
by Athanasius (Archbishop) on Feb 07, 2017 at 16:41 UTC

    Hello haukex,

    This is mostly good advice, but this part:

    • The regex /\b$team\b/ will match even if $team is only a substring of the string being searched.

    looks wrong to me: \b in a regex matches a word boundary, so substrings will not match:

    2:24 >perl -wE "for (qw[cat catastrophe]) { say qq[$_: matches] if /c +at/; }" cat: matches catastrophe: matches 2:26 >perl -wE "for (qw[cat catastrophe]) { say qq[$_: matches] if /\ +bcat\b/; }" cat: matches 2:26 >

    See “Assertions” under perlre#Regular-Expressions. But I agree that eq is better than a regex in this situtation, and a hash lookup would be preferable to using grep.

    Update: Anonymous Monk, below, makes an excellent point: some substrings will still match. A word boundary is defined as:

    a spot between two characters that has a \w on one side of it and a \W on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a \W.

    — and a hyphen is considered a “non-word” (i.e., it matches /\W/).

    Cheers,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Hi Athanasius,

      You're absolutely right of course. My intention was to warn that, if only exact matches are desired, "ABC DEF GHI"=~/\bDEF\b/ ("DEF" being a "substring" of "ABC DEF GHI") would give a false positive. But by omitting a discussion of \b, my node became inaccurate, so thank you for the reply :-)

      Thanks,
      -- Hauke D

      for (qw[cat catastrophe cat-ass-trophy]) { say qq[$_: matches] if /\bcat\b/ }