Sonal Asija Sonal Asija - 2 days ago 6
Perl Question

I want to add new line after every 4 spaces

i am generating 20 numbers and then i am shuffling it

perl -e 'foreach(1..20){print ",$_ "} '
| perl -MList::Util=shuffle -F',' -lane 'print shuffle @F'


and the output is:-


19 15 11 9 8 13 18 4 2 7 5 20 10 14 3 16 1 17 6 12


Now i want the output something like this:-


19 15 11 9

8 13 18 4

2 7 5 20

...


Any help will be appreciated

Answer

Doing that in several steps on the command line is ... strange. You can just do it in one program.

use strict;
use warnings;
use List::Util 'shuffle';

my $count = 1;
foreach my $i ( shuffle 1 .. 20) {
    print "$i ";
    print "\n\n" unless $count++ % 4;
}

This shuffles the list of 1 to 20 directly and then prints each item, but prints two linebreaks after every four. The % is the modulo operator that returns the left-over from a division by 4. So whenever the $count is divisible by 4, it returns 0, and the print kicks in. On the command line it would be like this:

$ perl -MList::Util=shuffle -e '$c=0; for (shuffle 1..20) { print"$_ "; print "\n\n" unless $c++%4}'

Here's the output:

11 20 8 17 

10 18 19 6 

1 14 7 5 

13 16 4 3 

9 2 15 12 
Comments