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

Need to visit each character in string value. I did like this .
use strict; use warnings; my $string = "Hello World"; my ($index,$a)= 0; for( ; $a = substr($string,$index,1) ; $index++) { print $a."\n"; }
Is there any other way to do this ?
Note : In php I used get like this
<? $string = "Hello World; echo $string{6}; ?>

Replies are listed 'Best First'.
Re: How to get each character in string value
by Punitha (Priest) on Dec 02, 2008 at 07:08 UTC

    You may want something like this?

    use strict; use warnings; my $string = "Hello World"; while($string =~/./g){ print "$&\n"; }

    Or,

    use strict; use warnings; my $string = "Hello World"; my @string = split(//,$string); for my $str (@string){ print "$str\n"; }

    Punitha

      According to perldoc perldata (paragraph for $MATCH) I would avoid the use of "$&"; I would capture the pattern and use "$1" instead.

      use strict; use warnings; my $string = "Hello World"; while($string =~/(.)/g){ print "$1\n"; }
      But usually I prefer the split() solution.
Re: How to get each character in string value
by poolpi (Hermit) on Dec 02, 2008 at 09:45 UTC
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @letters = unpack( "(a)*", 'Hello World' ); print Dumper \@letters; __END__ Output:$VAR1 = [ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' ];

    hth,
    PooLpi

    'Ebry haffa hoe hab im tik a bush'. Jamaican proverb
      If you want the output as array, you can use split and unpack, otherwise you can use pattern matching with /g flag in a while loop.
      example with unpack & character by character processing
      $string="Hello World"; $sum = 0; foreach $ascval (unpack("C*", $string)) { $sum += $ascval; } print "sum is $sum\n"; # prints "1052"
Re: How to get each character in string value
by apl (Monsignor) on Dec 02, 2008 at 13:09 UTC
    I favor the split method, myself, but if I was going to implement it the way you started, I'd go with:
    for my $index ( 0 .. length( $string ) - 1 ) { my $a = index( $string, $index, 1 ); # # do something }
    That is: you have a string, you know how long the string is, you should rely on that knowledge. What you did was more C-like than Perl-like.
Re: How to get each character in string value
by QM (Parson) on Dec 04, 2008 at 05:06 UTC
    If you just want the newlines after each char:
    $string = "Hello World"; print join("\n",split //,$string), "\n";

    But you can see that

    split //,$string

    is the black magic.

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

Re: How to get each character in string value
by repellent (Priest) on Dec 02, 2008 at 19:47 UTC
    my $string = "Hello World"; my $revcopy = reverse $string; print chop($revcopy) . "\n" for 1 .. length($string);

    while (defined(my $chr = chop $revcopy)) { print "$chr\n"; }

    Update: Corrected bug.