Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Breaking output lines into N-element chunks

by belden (Friar)
on Apr 11, 2002 at 18:20 UTC ( [id://158383]=note: print w/replies, xml ) Need Help??


in reply to Breaking output lines into N-element chunks

I've been having fun with the x operator lately. My first thought:

#!/usr/bin/perl use strict; use warnings; use constant LIMIT => 4; my @a = qw ( a bc def ghij klmno ); printf "%s " x LIMIT, @a; print "\n";
a bc def ghij

blyman
setenv EXINIT 'set noai ts=2'

Replies are listed 'Best First'.
Re: Re: Breaking output lines into N-element chunks
by Juerd (Abbot) on Apr 12, 2002 at 06:54 UTC

    printf "%s " x LIMIT, @a;

    That does some of the job, but only uses the first four (LIMIT) elements. To process an array in chunks, you need some sort of loop. The loop has to use an array index, or must destroy the array while running. Your solution is more or less equal to:

    print join ' ', @a[0..(LIMIT - 1)]; print " \n";
    This leaves alle elements in the array, and the indexes are constant (although you flatten the entire array, the general idea is using the first four (LIMIT) items, leaving the array intact).

    Solutions offered increase array indexes by four at a time, or destroy the array 4 elements at a time. The latter is done by looping until the array is empty (while it has elements), and spliceing to remove four elements. merlyn offered a compact solution that has the actual splice in the while-condition, which works because splice does not pad with undef elements, but actually returns an empty list when the array it spliced didn't have elements. The array assignment takes splices list and returns the array itself, which in scalar context evaluates to the number of elements. When the main array has no more elements, splice returns no elements, the array in scalar context returns 0, which is false so the loop stops.

    There is (as far as I know) no way to solve this without a smart loop.

    Yes, I reinvent wheels.
    

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://158383]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2024-04-18 15:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found