Search code examples
perlmojolicious

Access an array item in Perl after generating that array


Hello I want to access an specific array item based in a condition previously checked. I leave the code here:

elsif (scalar(@{$boss->bosses}) > 1) {
  foreach my $pa (@{$boss->bosses}) {
    my $p = My::Model::Group->new(id => $pa->group_id);
    push(@$groups, $p);
    $valid_pass = 1 if ($pa->checkPassword($self->param('password')));
  }  
  if ($valid_pass) {    
    my $pa_id = $pa->id;
    my $pa_partner_id = $pa->group_id;
  }
  else {
  }
}

What I want to do is, if that if in the array that comes, I check if the password is correct, so if it's correct, then I want to take the id and the group_id of the array item to use it in a function to be able to log them in.


Solution

  • Your for loop is doing two things at once: producing a list of My::Model::Group objects in @$groups, and finding the first boss whose password checks out.

    I suggest that you split them up into two clear operations, and the List::Util modules first operator is ideal for the second task

    Here's how it would look. I've extracted the result of the method call $boss->bosses into a variable $bosses to avoid repeated calls to the method

    Note that you don't need to apply scalar to an array when checking its size. The > and all the other comparators impose scalar context anyway

    I've taken much of my code from your question, and I'm a little concerned that you extract values for $pa_id and $pa_partner_id and then just discard them. But I imagine that you know what you really want to do here

    use List::Util 'first';
    
    my $bosses = $boss->bosses;
    
    if ( ... ) {
        ...;
    }
    elsif ( @$bosses > 1 ) {
    
        @$groups = map { My::Model::Group->new( id => $_->group_id ) } @$bosses;
    
        my $password = $self->param( 'password' );
        my $pa       = first { $_->checkPassword( $password ) } @$bosses;
    
        if ( $pa ) {    
            my $pa_id         = $pa->id;
            my $pa_partner_id = $pa->group_id;
        }
        else {
            ...;
        }
    }