http://www.perlmonks.org?node_id=843282


in reply to Re: Trouble grepping values when hash contains multiple values per key
in thread Trouble grepping values when hash contains multiple values per key

I see the problem now

I'm expecting grep to return true or false, but since this is a list context it will return the actual values. Is there any way to force grep to evaluate these in a scalar context in order to return a "true" or "false" in this case?

  • Comment on Re^2: Trouble grepping values when hash contains multiple values per key

Replies are listed 'Best First'.
Re^3: Trouble grepping values when hash contains multiple values per key
by chromatic (Archbishop) on Jun 05, 2010 at 19:47 UTC
    Is there any way to force grep to evaluate these in a scalar context in order to return a "true" or "false" in this case?

    Yes, evaluate grep in scalar context. It's that easy!

    my $found_any = grep { ... } @whatever;

    Boolean context is also a scalar context.

      my $found_any = grep { ... } @whatever;
      Because grep always iterates through the entire list, to stop on the first one found, you might try instead:
      use List::MoreUtils qw(any); my $found_any = any { ... } @whatever;
      or:
      use List::Util qw(first); my $found_any = defined first { ... } @whatever;
      ...though, in practice, it is unlikely to matter, performance-wise, unless @whatever is huge.

      As an aside, note that both any and first are built in to Perl 6.

Re^3: Trouble grepping values when hash contains multiple values per key
by toolic (Bishop) on Jun 05, 2010 at 17:38 UTC
    Is there any way to force grep to evaluate these in a scalar context in order to return a "true" or "false" in this case?
    Something like:
    my @date = grep ... if (@date) { ... }
Re^3: Trouble grepping values when hash contains multiple values per key
by dirtdog (Monk) on Jun 05, 2010 at 17:39 UTC

    I just changed the until loop to a while loop and now it's working as expected

    Sorry for wasting your time...I was not thinking clearly

    while (my @date = grep /$new_ex_date/,@{$countries{$cntry_of_issue}}) { $new_date=get_next_bus_day($new_date); }