Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print N array elements with delimiters per line?

Tags:

perl

I have an array in Perl I want to print with space delimiters between each element, except every 10th element which should be newline delimited. There aren't any spaces in the elements if that matters.

I've written a function to do it with for and a counter, but I wondered if there's a better/shorter/canonical Perl way, perhaps a special join syntax or similar.

My function to illustrate:

sub PrintArrayWithNewlines
{
    my $counter = 0;
    my $newlineIndex = shift @_;

    foreach my $item (@_)
    {
        ++$counter;
        print "$item";
        if($counter == $newlineIndex)
        {
            $counter = 0;
            print "\n";
        }
        else
        {
            print " ";
        }
    }
}
like image 986
Mark B Avatar asked Dec 31 '25 07:12

Mark B


2 Answers

I like splice for a job like this:

sub PrintArrayWithNewlines {
    my $n = 10;
    my $delim = " ";
    while (my @x = splice @_, 0, $n) {
        print join($delim, @x), "\n";
    }
}
like image 106
mob Avatar answered Jan 01 '26 21:01

mob


You can use List::MoreUtils::natatime:

use warnings; use strict;

use List::MoreUtils qw( natatime );

my @x = (1 .. 35);

my $it = natatime 10, @x;

while ( my @v = $it->() ) {
    print "@v\n"
}

Output:

C:\Temp> x
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35
like image 45
Sinan Ünür Avatar answered Jan 01 '26 23:01

Sinan Ünür



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!