On Mon, 1 Aug 2011 13:49:22 +0100
AKINLEYE <damola.akinl...@gmail.com> wrote:

> my @characters = split /[\s]/, $foo;
> foreach my  $letter(@characters )
> {
>    print $letter ;
> 
> }
> 
> or
> 
> my @characters = split /[\s]/, $foo;
> print join("\n" ,  @characters);
> 

That won't work because split/[\s]/ will split the string on any whitespace
character into words that don't contain whitespace. As a result:

<<<
shlomif:~$ perl -e 'print map { "$_\n" } split/[\s]/, "Big Brother From Afr"'
Big
Brother
From
Afr
shlomif:~$ 
>>>

To convert a string to characters one can use split based on the empty regex,
as Shawn showed:

<<<
shlomif:~$ perl -e 'print map { "$_\n" } split//, "Big Brother From Afr"'
B
i
g
 
B
r
o
t
h
e
r
 
F
r
o
m
 
A
f
r
>>>

One can also access individual characters without splitting and populating an
array using http://perldoc.perl.org/functions/substr.html . Here's a demo:

<<<
#!/usr/bin/perl

use strict;
use warnings;

my $s = "Big Brother From Afr";

foreach my $pos (0 .. length($s)-1)
{
    my $c = substr($s, $pos, 1);
    print "Character No. $pos = '$c'.\n"
}
>>>

> 
> Untested code though.
> 

Untested indeed, and please avoid top posting.

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Original Riddles - http://www.shlomifish.org/puzzles/

Comedy is simply a funny way of being serious.
    — http://en.wikiquote.org/wiki/Peter_Ustinov

Please reply to list if it's a mailing list post - http://shlom.in/reply .

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to