简体   繁体   中英

Perl pendant for Python Built-in Functions `all` and `any`

Are there Perl functions that work like Python functions all or any ? This answer from Jobin is a short explanation of how both functions are working.

I want to determine (without loop) if all error-msg's are defined and ne "" in the following structure:

$VAR1 = [{
  'row' => [{
      err_msg => "msg1",
      a => "a1",
      b => "b1"
    },
    {
      err_msg => "msg2",
      a => "a2",
      b => "b2"
    }]
},
{
  'row' => [{
      err_msg => "msg3",
      a => "a3",
      b => "b3"
    },
    {
      err_msg => "msg4",
      a => "a4",
      b => "b4"
    }]
}]

It's impossible to perform the check without looping, but you could indeed use all to do this.

use List::Util qw( all );

my $ok =
   all {
      all { $_->{err_msg} }
         @{ $_->{row} }
   }
      @$VAR1;

or

use List::Util qw( all );

my $ok =
   all { $_->{err_msg} }
      map { @{ $_->{row} } }
         @$VAR1;

The first version is more efficient because it only looks at a group if all the previous groups check out ok, whereas the second version unconditionally does work for every group. This difference is unlikely to matter, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM