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

How could I split every character, including any special characters (spaces, tabs, newlines, wide chars, etc) in a string and put them in an array? Thanks.

Replies are listed 'Best First'.
Re: split chars in string
by GrandFather (Saint) on Nov 23, 2009 at 04:27 UTC

    Why? Perl has very good string handling that generally works much faster on strings than any code that deals with characters one at a time. Tell us what you want to do and we can probably show you a Perlish way to achieve your end that runs much faster than dealing a character at a time.


    True laziness is hard work
      How about sorting an array of words by the second character of every word? Can that be achieved without splitting the words into characters?
        #!/usr/bin/perl use strict; use warnings; use 5.010; chomp( my @words = <DATA> ); @words = sort { substr( $a, 1, 1 ) cmp substr( $b, 1, 1 ) } @words; say for @words; __DATA__ How about sorting an array of words by the second character every word

        Just look at the second character.

        my @sorted_by_second = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, substr($_,1,1)] } @unsorted;
Re: split chars in string
by keszler (Priest) on Nov 23, 2009 at 04:21 UTC
Re: split chars in string
by colwellj (Monk) on Nov 23, 2009 at 04:20 UTC
    try
    split'[\w|\W]';
    Add codes if missing
    or
    my @array; for(0..$#string){ my $i = $_; push @array,substr($string,$1,1); }
      I'm not sure why you would want to split on word or non-word characters ([\w|\W]) instead of on an empty string:
      $ perl -e 'print "$_\n" for split "", "foo"' f o o
      But, as GrandFather already pointed out, if you think you want to process a string character-by-character in Perl, then the odds are pretty good that you're doing it wrong.
      You're mixing two concepts together. When you said
      split /[\w|\W]/

      you meant

      split /[\w\W]/

      or

      split /\w|\W/

      The above would be better written as

      split /./s

      That said, it doesn't work. If you want to separate every character, the characters aren't the separators, the nothings between each character are. You want:

      split //, $x

      The following would also do:

      $x =~ /./sg
Re: split chars in string
by colwellj (Monk) on Nov 23, 2009 at 04:20 UTC
    try
    split'[\w|\W]';
    Add codes if missing
    or
    my @array; for(0..$#string){ my $i = $_; push @array,substr($string,$1,1); }