Parsing a string character by character in Perl

I want to parse a string character by character. I use perl for this. Is there a way by which we can start with the first character of the string and then quote the 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 combining the wholes string in front of you, is there a handle that points to the first character of the string and then crosses each character? Is there any way to do this?

+4
source share
3 answers

It could be a skeleton 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 result:

$VAR1 = [
      'The story of Dr. W. Fletcher who is a dentist',
      undef,
      ' The hero of the community'
    ];
+1
source
my $var = "junk sit here. fkuc lkasjdfie.";

while ($var =~ /(.)/sg) {
   my $char = $1;
   # do something with $char 
}

or

for my $i (1 .. length $var) {
  my $char = substr($var, $i-1, 1);
}

and when scanning, the method substrworks better than while,

use Benchmark qw( cmpthese ) ;
my $var = "junk sit here. fkuc lkasjdfie." x1000;

cmpthese( -5, {
    "while" => sub{
      while ($var =~ /(.)/sg) {
         my $char = $1;
         # do something with $char 
      }
    },
    "substr" => sub{
      for my $i (1 .. length $var) {
        my $char = substr($var, $i-1, 1);
      }
    },
});

result

         Rate  while substr
while  56.3/s     --   -53%
substr  121/s   114%     --
+2
source

, , , reverse chop , .

$a = "dude"; 
$b = reverse($a); 
for ($i = length($b) ; $i>0 ; $i--) {
  print chop $b; print "\n";'
}
+1

Source: https://habr.com/ru/post/1538247/


All Articles