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

How do I change a string to an array without using the split function. I want to change a whole word to an array without splitting it using some regular character, like ":". For example, I want to change "millenium" into an array.

Replies are listed 'Best First'.
Re: Arrays and strings
by Juerd (Abbot) on May 26, 2002 at 13:51 UTC

    I want to change a whole word to an array without splitting it using some regular character, like ":".

    Use an empty pattern then:

    my @array = split //, $string;

    - Yes, I reinvent wheels.
    - Spam: Visit eurotraQ.
    

Re: Arrays and strings
by choocroot (Friar) on May 26, 2002 at 14:08 UTC
    Using the m// operator ?
    my $string = "millenium"; my @list = ( $string =~ m/./g ); foreach my $char (@list) { print "$char\n"; }
    Output:
    m i l l e n i u m
(jeffa) Re: Arrays and strings
by jeffa (Bishop) on May 26, 2002 at 16:57 UTC
    The ugly way:
    my $str = 'millenium'; my @array = map {chr} unpack 'C*',$str;
    If this is homework, then be prepared to explain how it works. ;)

    (and yes, i will gladly explain if it is not)

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Arrays and strings
by bjelli (Pilgrim) on May 26, 2002 at 17:43 UTC

    anonymous didn't say he wanted to make an array of the single characters, did he? I invoke the first virtue of programming and go for:

    @a = ("millenium");

    --
    Brigitte    'I never met a chocolate I didnt like'    Jellinek
    http://www.horus.com/~bjelli/         http://perlwelt.horus.at
Re: Arrays and strings
by chromatic (Archbishop) on May 26, 2002 at 21:50 UTC
    I've taken the liberty of correcting your typo. This is the most literal approach of what you've asked:
    my $word = 'millennium'; { no strict 'refs'; @$word = (); }
    It's generally considered better form to use a hash, however.
    my %arraysfromwords; $arraysfromwords{ $word } = [];
    Of course, since split predates references in Perl, you may still be stuck.

    Another option is to upgrade to a modern version of Perl with a working split, and use Inline::C. Since a string in C can be treated as an array of char pointers, all you have to do is to pass the SV to C, extract the string, create a new AV, and populate it with pointers to the new SVs representing each character.

    I'd probably just use split though, and save myself thirty seconds.

Re: Arrays and strings
by mattr (Curate) on May 26, 2002 at 13:46 UTC
    why? this ain't C.

    I can't test if split '' would work, but certainly you could just read your string a byte at a time with substring and push it into an array. if it was on disk you could access it with a read function.. homework? urk.