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

I want to create this string programmatically:
$x = "\n1 2 3\n4 5 6\n7 8 9";
But I cant figure out a nice concise way to do it? Help please.

Replies are listed 'Best First'.
Re: Programmatic creation of iterated string
by Boogman (Scribe) on Aug 18, 2000 at 20:31 UTC
    In the chatterbox you said
    map { $_ .. $_+2 } (1,4,7) is what I mean to put to clarify what you meant to say. You could try: $x = "\n".join "\n", map { join ' ', ( $_ .. $_ + 2 ) } ( 1, 4, 7 ); Is that what you wanted to have?
      And that's cool code, but it's a lot more typing than just the static string!

      What I tried to get at in the chatter box is that we have only one example to work from, and no rules or specification. We don't know if princepawn wants "any N by N matrix as a text string" or "reshape the numbers 1 through 9 in different orientations". There's nothing "programmatic" about a text string, even as a solitary example.

      Most of the hard work of programming is just getting the specification right. The easy part is the coding!

      -- Randal L. Schwartz, Perl hacker

Re: Programmatic creation of iterated string
by lhoward (Vicar) on Aug 18, 2000 at 20:32 UTC
    I think what you're looking for is something like this:
    my $x=''; for(1..9){ $x.="\n" if $_%3==1; $x.= $_.' '; }
    I'm not really sure because there are many diffrent ways to generate the single example of the pattern you are looking for. Can you describe the pattern you want instead of giving a single example?
RE: Programmatic creation of iterated string
by merlyn (Sage) on Aug 18, 2000 at 20:11 UTC
Re: Programmatic creation of iterated string
by fundflow (Chaplain) on Aug 18, 2000 at 20:35 UTC
    Do you mean something like this:
    my $s=""; for (1,4,7) { $s .= join(" ", $_ .. $_+2) . "\n";}
    For a general K*K, you can do
    $K=5; for (1 .. $K*$K) { $s.= ( $_ % $K ? "$_ " : "$_\n"); }


Re: Programmatic creation of iterated string
by athomason (Curate) on Aug 18, 2000 at 20:43 UTC
    Here's a more general answer, though if you can wait for Perl 6, the weave (zip, or whatever) operator will be builtin or at least in a module instead of a hacked sub:
    my $n = 30; print weave([map{$_%3?' ':"\n"}0..$n-1],[1..$n]); sub weave { my @t; { @$_ ? push @t, shift @$_ : return @t for @_; redo; } }
A reply falls below the community's threshold of quality. You may see it by logging in.