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

Hello! I'm still trying to learn Perl in my spare time.

The following code is a simple example of a larger problem I am having. I am trying to transpose a string of characters from a horizontal scalar to a vertical string of characters.

ie) ABCDEFG to:

A

B

C

D

E etc

The code below almost gives me what I want but there is one error message that appliers with each character: Argument "character" isn't numeric in array element at C\:dir line 8. Any help on this simple problem would be nice!!

#!/usr/bin/perl use strict; use warnings; my $phrase="I like apple pie"; #### set the phrase my @array = split(//, $phrase);### split phrase into individual charac +hters### foreach my $w (@array){ print "$array[$w]\n"; };
Thanks in advance for your help!!

Replies are listed 'Best First'.
Re: Transposing an Array
by Arunbear (Prior) on Nov 11, 2004 at 21:57 UTC
    Try this:
    print join "\n", split(//, $phrase);
      Or:
      $,="\n"; print split //, $phrase;
      to avoid the join :-)
      BTW, a one-liner could be:
      perl -le 'print for split //, pop' "my phrase here"
      Paul
Re: Transposing an Array
by tachyon (Chancellor) on Nov 11, 2004 at 22:33 UTC

    Another way, no array required

    $_ = "ABCDEFG"; s/(.)/$1\n/g; print;

    cheers

    tachyon

Re: Transposing an Array
by ikegami (Patriarch) on Nov 11, 2004 at 21:40 UTC

    $w holds $array[index], not index, so just use print "$w\n";. If you do want $w to hold the index, do:

    foreach my $w (0..$#array){ print "$array[$w]\n"; };
Re: Transposing an Array
by atcroft (Abbot) on Nov 11, 2004 at 22:02 UTC

    Just for grins, this also will work:

    $phrase = join("\n", split(//, $phrase)); print $phrase, "\n";

    This does the split as before, but then joins them back into a single string with the "\n" character as the seperator. 'Njoy.

Re: Transposing an Array
by gube (Parson) on Nov 12, 2004 at 10:08 UTC
    <!--PLEASE TRY THESE CODE> <!--THE ABOVE INFORMED IN ANONYMOUS IS GUBE>
    use strict; my($input,@input); $input = <STDIN>; @input = split(//, $input); $" ="\n"; print "@input";
      Thanks for the idea, but I don't quite understand what <code> $"="\n"; <code> is from. I haven't see it in Learning Perl and I'll have to read how it works with the string. It is a nice trick, it seems like a shortcut to concatenate a common command to every string in the array.
Re: Transposing an Array
by Anonymous Monk on Nov 12, 2004 at 09:58 UTC
    <!--please try this code :) >
    $input = <stdin>; @input = split(//, $input); $" ="\n"; print "@input";
Re: Transposing an Array
by TedPride (Priest) on Nov 12, 2004 at 07:48 UTC
    Or:
    my $str = 'ABCDEFG'; for (0..(length($str)-1)) { print substr($str,$_,1)."\n"; }
    I just like substr :)