Dear Monks
if I will to delete the certain element of an array I could do the following:
#!/usr/bin/perl
use strict;
use warnings;
use List::MoreUtils qw(first_index);
my @array = ( 10, 15, 20, 25, 30, 20 );
my $test = 25;
purge_this_one( \@array, $test );
print "@array\n";
sub purge_this_one
{
my $idx = first_index { $_ == $_[1] } @{$_[0]};
return @{$_[0]} if $idx == -1; # added (s.Update)
splice( @{$_[0]}, $idx, 1 );
return @{$_[0]};
}
Now I try to perform the same thing in an object whose elements are another objects. As a very simple-level Perl programmer I failed miserably and I would be very grateful for your help.
Here is the code (minimal working example) with comments in the problem part:
#!/usr/bin/perl
use strict;
use warnings;
package Person;
use Moose;
use constant DURATION => 100;
has use_duration => ( isa => 'Int', is => 'ro', default => 1);
has frequency => ( isa => 'Int', is => 'ro', default => 50 );
has population => (
handles => {obtain => 'push',
release => 'shift',
inventory => 'count',
find => 'first_index',
purge => 'delete'},
isa => 'ArrayRef[Person]',
default => sub{ [] },
traits => ['Array'],
is => 'ro',
);
has number => ( isa => 'Int', is => 'rw', default => 0);
sub need_to_go
{
my $self = shift;
return ( rand(DURATION)+1 <= $self->frequency) ? 1 : 0;
}
no Moose;
package main;
use Data::Dumper;
my $people_nr = 25;
my $people = Person->new;
for my $case ( 1 .. $people_nr )
{
my $per = Person->new;
$per->number( $case );
$people->obtain( $per );
}
for my $p ( @{ $people->population } )
{
if ($p->need_to_go)
{
# My problem is here.
# I suppose to use
# first_index( sub { ... }) method
# and then delete or splice
# but I cannot figure out what to feed
# the sub { ... } with
}
}
print Dumper $people;
Thank you in advance!
VE
Update: Improved the subroutine purge_this_one by adding the line
return @{$_[0]} if $idx == -1; after comment from
sundialsvc4
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.