-1

I have an array in the format:

@arr = ABHCKPDLT OJEWFNONP POJEWPOFJ IWOJEFPPW IHWEF_IPIA

I need to check is the number of elements limit say 4k characters, is reached. If so, a new array has to be created and store next limit of arrays.

@arr_final = [[ABHCKPDLT OJEWFNONP POJEWPOFJ],[IWOJEFPPW IHWEF_IPIA]]

 #!usr/bin/perl
 use List::MoreUtils qw(natatime);
 my @VAR;
 {
  my $iter = natatime 3, @arr;
  while( my @tmp = $iter->() ){
    push @VAR, \@tmp;
  }
 }

Please suggest what would be best approach in perl.

5
  • 4
    Please, show real code, not a random syntax that doesn't work in Perl. Do you have an array, or an array of arrays? What should happen to the old array when a new one is created? Commented Jul 14, 2020 at 8:15
  • Old array has to be updated as the one in @arr_final. I have an array and I need array of arrays. I am beginner and have used as per suggestion in stackoverflow.com/questions/1490896/… but doesn't work Commented Jul 14, 2020 at 8:18
  • 3
    @Neetu: Please show us your actual code. Commented Jul 14, 2020 at 8:25
  • 2
    @Neetu When you click on the "edit" link below the question you'll be able to change it -- please add your code that shows how you attempt this. Saying "but doesn't work" just does not help at all. Commented Jul 14, 2020 at 8:30
  • Something is still unclear. You're using natatime() to extract three elements at a time from your array. So where does the 4K character limitation come in? Commented Jul 14, 2020 at 10:19

1 Answer 1

2

Keep the character count in a variable, reset it when starting a new subarray.

#!/usr/bin/perl
use strict;
use warnings;

my $THRESHOLD = 15;

my @arr = qw( 123456789 123456 123456789 132 123456789 1234 123456789 12345 1234567890 );

my @final = ([]);
my $size = 0;
while (@arr) {
    $size += length $arr[0];
    if ($size > $THRESHOLD) {
        $size = length $arr[0];
        push @final, [];
    }
    push @{ $final[-1] }, shift @arr;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfect. Thank you @choroba. This is of great help. Print statement : print "@$_\n" for @final;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.