Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi
if i have an array @arry which have 200 items, and i want to replace the values in many arbitrary positions in the @array whith the number 15, i seek other concise approaches please,
i am doing it like this:
$arry[73]=15; $arry[120]=15; $arry[124]=15; $arry[170]=15; $arry[31]=15;$arry[32]=15;$arry[60]=15;$arry[199]=15;$arry[63]=15;

Replies are listed 'Best First'.
Re: replacing many items in an array
by moritz (Cardinal) on Jan 24, 2008 at 09:02 UTC
    If you have a list or array with the indexes that need to be replaced, you can use an array slice:
    my @repl = (73, 120, 124, 170, ... ); @arry[@repl] = (15) x @repl;

    Or of course a simple loop will do as well:

    for (@repl) { $arry[$_] = 15; }
Re: replacing many items in an array
by jwkrahn (Abbot) on Jan 24, 2008 at 09:13 UTC
    $arry[ $_ ] = 15 for 73, 120, 124, 170, 31, 32, 60, 199, 63; $_ = 15 for @arry[ 73, 120, 124, 170, 31, 32, 60, 199, 63 ];
Re: replacing many items in an array
by olus (Curate) on Jan 24, 2008 at 11:23 UTC
    If you really want arbitrary positions for every time you run the code, I suggest the following:
    my $number_of_positions = 10; my @positions = (1..200); for my $i (1..$number_of_positions) { $arry[splice(@positions, rand(@positions), 1)] = 15; }
    Or with a map
    my $number_of_positions = 10; my @positions = (1..200); map {$arry[splice(@positions, rand(@positions, 1)] = 15;} (1..$number_ +of_positions);
    You just have to tell how many positions you want to be changed.
Re: replacing many items in an array
by parv (Parson) on Jan 24, 2008 at 09:03 UTC

    Use array slice ...

    @p[ 1 , 3 , 5 ] = ( 0 , 2 , 4 );

    Whoops... Corrected the delimiters for the slice. So much for linking to perldata, let alone giving advice. (Shame, shame!)