heidi has asked for the wisdom of the Perl Monks concerning the following question:

hi monks.. i want to print a string of alphabets, 8 in a line.
for example: $str=abcdabcdabcdabcdabcdabcd is a string I want it to be printed as,8 in a line abcdabcd abcdabcd abcdabcd
plz give me a solution. thanks.

Replies are listed 'Best First'.
Re: 8 in a line...
by moritz (Cardinal) on Jun 20, 2008 at 09:56 UTC
    { local $\ = "\n"; print for unpack '(A8)*', $str; }
Re: 8 in a line...
by cdarke (Prior) on Jun 20, 2008 at 10:01 UTC
    TMTOWTDI. Here is a format solution:
    use strict; use warnings; my $str='abcdabcdabcdabcdabcdabcd'; write; format = ^<<<<<<< ~~ $str .
Re: 8 in a line...
by grinder (Bishop) on Jun 20, 2008 at 13:42 UTC

    I'd probably go the unpack route, but walking down substrings is sometimes faster.

    use constant CHUNK => 8; for (my $x = 0; $x < length($str) / CHUNK; ++$x) { print substr($str, $x * CHUNK, CHUNK), "\n"; }

    For people who have an aversion to C-style loops in Perl, the above can also be recast as a statement modifier:

    print substr($str, $_ * CHUNK, CHUNK), "\n" for 0 .. length($str) / CHUNK;

    • another intruder with the mooring in the heart of the Perl

Re: 8 in a line...
by apl (Monsignor) on Jun 20, 2008 at 12:48 UTC
    How did you try to answer the question?
Re: 8 in a line...
by Anonymous Monk on Jun 20, 2008 at 10:15 UTC
    Some regex approaches:

    perl -wMstrict -e "my $str = 'abcdabcdabcdabcdabcdabcd'; print join qq(\n), $str =~ /.{8}/g, qq(\n); my $alphabet = qr{ abcd }xms; print join qq(\n), $str =~ /$alphabet$alphabet/g, qq(\n); print join qq(\n), $str =~ /$alphabet{2}/g, qq(\n); " abcdabcd abcdabcd abcdabcd abcdabcd abcdabcd abcdabcd abcdabcd abcdabcd abcdabcd
      print join qq(\n), $str =~ /.{8}/g, qq(\n);

      In the general case you need an /s modifier in that regex (but it's hard to tell from heidis post if you need in this specific case).

Re: 8 in a line...
by waldner (Beadle) on Jun 21, 2008 at 08:52 UTC
    Since noone has posted this, here it is:
    $str=~s/.{8}/$&\n/g;