pythonperlperl-data-structures

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"
    }]
}]

Solution

  • 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.