如何把一个字符串分解成单个字符

如何把一个字符串分解成单个字符

如题
perl -e '$_ = "abcdefg"; s/(.)/$1\n/g; print'
perl -e '$_ = "how are you 2008";s/ *(\S)/$1\n/g;print'

split //, "abcdef"
unpack   
多谢楼上诸位。仔细google了一下,转一篇http://www.perlmeme.org/faqs/man ... ing_characters.html的文章总结一下
Solution 1: split

If you pass no seperator into split, it will split on every character:

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";

    my @chars = split("", $string);

    print "First character: $chars[0]\n";

The output of this program is:

    First character: H

Solution 2: substr

You can access an individual character using substr:

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";
    my $char = substr($string, 7, 1);

    print "Char is: $char\n";

The above code would output:

    Char is: h

Solution 3: Unpack

Like substr, if you want a character from a particular position, you can use unpack:

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";
    my $char = unpack("x9a1", $string);

    print "Char is: $char\n";

The output of this program is:

    Char is: w

Solution 4: substr and map

If you want to access all the characters individually, you can build them into an array (like Solution 1) using substr and map:

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";
    my @chars = map substr( $string, $_, 1), 0 .. length($string) -1;

    print "First char is: " . $chars[0] . "\n";

    exit 0;

The output of this example would be:

    First char is: H

Solution 5: Regular expression

You can use a regular expression to build an array of chars:

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";
    my @chars = $string =~ /./sg;

    print "Fourth char: " . $chars[3] . "\n";

    exit 0;

The output of this program is:

    Fourth char: l

Solution 6: unpack

unpack can also unpack individual chars into an array:

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";
    my @chars = unpack 'a' x length $string, $string;

    print "Eighth char: $chars[7]\n";

    exit 0;

The output would be:

    Eighth char: h

See also

    perldoc -f split
    perldoc -f substr
    perldoc -f pack
    perldoc -f unpack
google 得力量是强大得
there is more than one way to do it