Search code examples
perl

Parsing a string character by character in Perl


I want to parse a string character by character. I am using perl to do that. Is there any way where we can start from the first character of the string and then loop character by character. Right now I have split the string into an array and I am loo[ping through the array.

$var="junk shit here. fkuc lkasjdfie.";
@chars=split("",$var);

But instead of spliting the wholes string before itself, is there any descriptor which would point to the first character of the string and then traverse each character? Is there any way to do this?


Solution

  • This can be the skeleton of the script/regex:

    use strict;
    use warnings;
    use Data::Dumper qw(Dumper);
    
    my $str = "The story of Dr. W. Fletcher who is a dentist. The hero of the community.";
    
    my @sentences = split /(?<!(Dr| \w))\./, $str;
    print Dumper \@sentences;
    

    And the output is:

    $VAR1 = [
          'The story of Dr. W. Fletcher who is a dentist',
          undef,
          ' The hero of the community'
        ];