http://www.perlmonks.org?node_id=723559


in reply to printing 20 characters in a line.

You can do like this, if the number of character is fixed

#!/usr/bin/perl use strict; use warnings; my $str="30 30 36 33 36 36 36 33 36 34 26 24 21 17 17 23 27 27 31 31 3 +4 33 33 33 36 36 37 38 38 38 38 38 35 40 34 34 34 31 37 36 37 37 40 4 +0 49 40 40 40 40 40 40 40 40 33 30 30 30 30 30 42 45 45 45 45 45 49 4 +2 42"; open (OUT,">format.out"); my @array=split(/ /,$str); for (0..19){ print OUT "$array[$_] "; } close(OUT);

Punitha

Updated after the reply from heidi

I misunderstood the question, thanks for the reply heidi. So here is the code you needed,

#!/usr/bin/perl use strict; use warnings; my $str="30 30 36 33 36 36 36 33 36 34 26 24 21 17 17 23 27 27 31 31 3 +4 33 33 33 36 36 37 38 38 38 38 38 35 40 34 34 34 31 37 36 37 37 40 4 +0 49 40 40 40 40 40 40 40 40 33 30 30 30 30 30 42 45 45 45 45 45 49 4 +2 42"; open (OUT,">format.out"); my @array=split(/ /,$str); my $cnt=0; foreach (0..$#array){ ++$cnt; if ($cnt % 20 == 0){ print OUT "$array[$_]\n"; } else{ print OUT "$array[$_] "; } } close(OUT);

Punitha

Replies are listed 'Best First'.
Re^2: printing 20 characters in a line.
by ikegami (Patriarch) on Nov 14, 2008 at 06:11 UTC
    Either you don't need $cnt, or you don't need to iterate over the indexes.
    for (0..$#array){ if ($_ % 20 == 19){ print OUT "$array[$_]\n"; } else{ print OUT "$array[$_] "; } }
    for (@array){ if (++$cnt % 20 == 0){ print OUT "$_\n"; } else{ print OUT "$_ "; } }

    It's probably worth noting the last line has a trailing space and isn't terminated.

Re^2: printing 20 characters in a line.
by heidi (Sexton) on Nov 14, 2008 at 04:55 UTC
    ooopzz, you got me wrong. The whole string has to be printed line by line. Not only the first line. sorry for not giving the expected output format. here it is
    30 30 36 33 36 36 36 33 36 34 26 24 21 17 17 23 27 27 31 31 34 33 33 33 36 36 37 38 38 38 38 38 35 40 34 34 34 31 37 36 37 37 40 40 49 40 40 40 40 40 40 40 40 33 30 30 30 30 30 42 45 45 45 45 45 49 42 42