checking if condition in foreach in perl if not matching push to array

353 Views Asked by At

I am using Perl

I have a string (comma separated), then looping this in a foreach. In the foreach I am checking each item if it exists. And here comes the tricky part.

If an item does not exist, I want to push that to a comma separated string or array and continue to the next item.

At the moment the code I use, doesn't do that.

Here is what I have so far:

my @cnames = split(',', $comma_separated_values;
foreach my $cname (@cnames) {
    my @records_to_change = "function to check the cname";
    if (@records_to_change) {
        $records_to_change[0]->set_google_maps_key($google_maps_key || '');
        $records_to_change[0]->set_https_only( $https_only );
    }else{
        FAILED { 'success' => 0 };
    }
    $records_to_change[0]->update();
}

With this code, if an item doesn't exist, it stops, display an error message (not described here) and won't continue.

Any idea how to do this?

1

There are 1 best solutions below

1
On BEST ANSWER

The code you posted doesn't even compile (missing closing parenthesis).

It's not clear what the hand-waved "function to check the cname" returns, so I have no idea what goes wrong. But generally, the logic is correct and should work:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

sub check_existence {
    exists {a => 12, c => 14}->{ $_[0] }
}

my $comma_separated_values = 'a,b,c,d';

my @cnames = split /,/, $comma_separated_values;
my @missing;
foreach my $cname (@cnames) {
    if (check_existence($cname)) {
        say "$cname is ok.";
    } else {
        push @missing, $cname;
    }
}
say 'Missing: ', join ', ', @missing;