سؤال

I can delete table entries with this code:

foreach my $id (@$idarray) { #idarray is an array reference
$c->model('My::DB')->find($id)->delete;
}

That above code only works when @$idarray holds more than one value, but it fails when only 1 value is contained. Some ideas guys?

The error when i only delete 1 entry is:

Can't use string ("61") as an ARRAY ref while "strict refs" in use

61 there is just an example. Represents the $id

sample idarray values: $idarray = [61, 1, 2, 3];

هل كانت مفيدة؟

المحلول 2

The error message says that value 61 are used as array refernce, that means in case of single value, I think $idarray contains only one value, not array refernce, meaning that try to do it like

if( ref $idarray eq 'ARRAY') {
    foreach my $id (@$idarray) { #idarray is an array reference
    $c->model('My::DB')->find($id)->delete;
} else{
    $c->model('My::DB')->find( $idarray )->delete;
}

نصائح أخرى

You can better do this as:

$c->model('My::DB')->search({ 'id' => $idarray })->delete_all;

DBIx::Class will automatically detect whether you pass in a single value or array ref and do the right thing. This will also generate a single delete statement for your DB which will may more efficient than doing multiple single deletes in your RDBMS.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top