http://qs1969.pair.com?node_id=803507

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

Hi, i have an array from which i would like to put the every 5th element to another array.
how can this be done.
example myarray (1,2,3,4,5,6,7,8,sd,frd,sed,sddfsd,asecf,ssdd,myh)
i want sub array like (5,frd,myh)

• Comment on how to push 5th element from one array to another array

Replies are listed 'Best First'.
Re: how to push 5th element from one array to another array
by ctilmes (Vicar) on Oct 27, 2009 at 20:14 UTC
```my @arr = qw(1 2 3 4 5 6 7 8 sd frd sed sddfsd asecf ssdd myh);
my \$i = 1;
my @arr2 = grep { \$i++ % 5 == 0 } @arr;
Re: how to push 5th element from one array to another array
by ikegami (Patriarch) on Oct 27, 2009 at 20:46 UTC

And now for something completely different

```my @array = ...;
splice(@array, \$_, 4) for 0..\$#array/5;
print("@array\n");
Re: how to push 5th element from one array to another array
by jettero (Monsignor) on Oct 27, 2009 at 20:11 UTC
Re: how to push 5th element from one array to another array
by gmargo (Hermit) on Oct 27, 2009 at 20:14 UTC

Homework? You just need a simple loop.

```my @myarray = qw(1 2 3 4 5 6 7 8 sd frd sed sddfsd asecf ssdd myh);
my @fifth;

for (my \$i=4; \$i < scalar(@myarray); \$i += 5)
{
push(@fifth, \$myarray[\$i]);
}

print "fifth=".join(",",@fifth)."\n";
Re: how to push 5th element from one array to another array
by merlyn (Sage) on Oct 27, 2009 at 20:23 UTC
Fifth Element? :)

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

So
```use LWP::Simple;
push @array, get('http://t0.gstatic.com/images?q=tbn:T8Bsbbf6vqMr9M:ht
+-%2520Fifth%2520Element.jpg');
?
Re: how to push 5th element from one array to another array
by NetWallah (Canon) on Oct 28, 2009 at 00:31 UTC
Slicy (Pretty efficient):
```   my @fifth =  @arr[ map {\$_*5-1} 1..\$#arr+4/5 ];
Update: See gmargo's (++) correction below.

Potentia vobiscum ! (Si hoc legere scis nimium eruditionis habes)

```my @fifth =  @arr[ map {\$_*5-1} 1..\$#arr+4/5 ];
```my @fifth =  @arr[ map {\$_*5-1} 1..(\$#arr+4)/5 ];
```my @fifth =  @arr[ map {\$_*5-1} 1..(\$#arr+1)/5 ];