xyz123
xyz123

Reputation: 651

Splitting an Array into n accessible parts within perl?

My goal is to take an array of letters and cut it up into "n" parts. In this case no more than 10 letters each piece. But I want these arrays to be stored into an array reference which I can access on a counter.

For example, I have the following script to split an array of English alphabetical letters into 1 array of 10 letters. But since the English Alphabet has 26 letters, I need 2 more arrays to access in an array reference.

#!/usr/bin/env perl
#split an array into parts. 
use strict;
use warnings;
use feature 'say';

my @letters = ('A' .. 'Z');
say "These are my letters:";
for(@letters){print "$_  ";}

my @letters_selected = splice(@letters, 0, 10);
say "\nThese are my selected letters:";
for(@letters_selected){print "$_  ";}

The output is this: These are my letters:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

These are my selected letters:

A B C D E F G H I J

This little script only gives me one piece of 10 letters of the alphabet. But I want all three pieces of 10 letters of the alphabet, so I would like to know how I can achieve this:

Goal: Have an array reference called letters_selected of letters which contains all letters A - Z. But ... I can access all three pieces of size less than or equal to 10 letters like this.

  foreach(@{$letters_selected[0]}){say "$_  ";}

returns: A B C D E F G H I J # These are the initial 10 elements of the alphabet.

foreach(@{$letters_selected[1]}){say "$_  ";}

returns: K L M N O P Q R S T # The next 10 after that.

foreach(@{$letters_selected[2]}){say "$_  ";}

returns: U V W X Y Z # The next no more than 10 after that.

Upvotes: 1

Views: 1297

Answers (1)

zdim
zdim

Reputation: 66873

Since splice is destructive to its target you can keep applying it

use warnings;
use strict;
use feature 'say';

my @letters = 'A'..'Z';

my @letter_groups;

push @letter_groups, [ splice @letters, 0, 10 ]  while @letters;

say "@$_" for @letter_groups;

After this @letters is empty. So make a copy of it and work with that if you will need it.


Every time through, splice removes and returns elements from @letters and [ ] makes an anonymous array of that list. This reference is pushed on @letter_groups.

Since splice takes as many elements as there are (if there aren't 10) once fewer than 10 remain splice removes and returns that, the @letters gets emptied, and while terminates.

Upvotes: 3

Related Questions