fork download
  1. #!/usr/bin/perl
  2. # Idiom #321 Access character in string, by index
  3.  
  4. # https://w...content-available-to-author-only...s.org/idiom/321/access-character-in-string-by-index
  5. #
  6.  
  7. use v5.10;
  8.  
  9. use open qw( :std :utf8 );
  10.  
  11. my $s;
  12. my @chars;
  13.  
  14. use utf8;
  15.  
  16. say "Using utf8:";
  17. $s = '01ā3€5';
  18. say "the input string is: ", $s;
  19. say "it's length is: ", length $s;
  20. @chars = split //, $s;
  21. foreach my $i (0..$#chars) {
  22. printf "the %dth character is %s\n", $i, substr $s, $i, 1;
  23. }
  24.  
  25. say '-' x 10;
  26.  
  27. no utf8;
  28. $s = '01ā3€5';
  29. say "Without using utf8:";
  30. say "the input string is: ", $s;
  31. say "it's length is: ", length $s;
  32. @chars = split //, $s;
  33. foreach my $i (0..$#chars) {
  34. printf "the %dth character is %s\n", $i, substr $s, $i, 1;
  35. }
  36.  
  37.  
  38.  
Success #stdin #stdout 0.01s 5508KB
stdin
Standard input is empty
stdout
Using utf8:
the input string is: 01ā3€5
it's length is: 6
the 0th character is 0
the 1th character is 1
the 2th character is ā
the 3th character is 3
the 4th character is €
the 5th character is 5
----------
Without using utf8:
the input string is: 01ā3€5
it's length is: 9
the 0th character is 0
the 1th character is 1
the 2th character is Ä
the 3th character is 
the 4th character is 3
the 5th character is â
the 6th character is ‚
the 7th character is ¬
the 8th character is 5