[Perl] Good reasons to use regex?

Gabor Szabo gabor at perl.org.il
Tue Jun 10 05:28:22 PDT 2003


On Tue, 10 Jun 2003, Gabor Szabo wrote:
> Pick up a few of the regexes you wrote lately and try to express them 
> in another way in Perl.

Let me bring an example here.

A very basic task is to remove white spaces from the beginning and the end 
of a string and to reduce the white spaces in the middle to only one
character. Here is my example code:
I'd be glad if you found bugs or better solutions.
    Gabor


my @strs = (
     "first    last", 
     "   somespace   more space    ", 
     "\t\t  include\ttabs\t \t as well\t \t", 
     "   ");
###############################################

my @str = @strs;
foreach my $s (@str) {
    print "'$s'\n";
    $s = remove_leading_space($s);
    print "'$s'\n";
    $s = remove_trailing_space($s);
    print "'$s'\n";
    $s = reduce_space($s);
    print "'$s'\n";
    print "=======================\n";
}

sub remove_leading_space {
    my $s = shift;
    my $i=0;
    my $l = length $s;
    while ($i < $l) {
       my $c = substr($s, $i, 1);
       last if (not grep {$_ eq $c} (" " , "\t", "\f", "\n", "\r"));
       $i++;
    }     
    substr($s, 0, $i, '');
    return $s;
}

sub remove_trailing_space {
    my $s = shift;
    my $i=0;
    my $l = length $s;
    while ($i < $l) {
       my $c = substr($s,  - $i -1, 1);
       last if (not grep {$_ eq $c} (" " , "\t", "\f", "\n", "\r"));
       $i++;
    }
    substr($s, -$i, $i, '');
    return $s;
}

sub reduce_space {
    my $s = shift;

    my $i = 0;
    while ($i < length($s)-1) {
       my $c = substr ($s, $i, 1); 
       if (not grep {$_ eq $c} (" " , "\t", "\f", "\n", "\r")) {
          $i++;
	  next; # skip if not white space
       }
       $c = substr ($s, $i+1, 1); 
       if (not grep {$_ eq $c} (" " , "\t", "\f", "\n", "\r")) {
          substr($s, $i, 1, ' '); # make sure it is a space
          $i+=2;
          next; # skip two if next is not white space
       }
       substr($s, $i, 1, ''); # cut off one white space 
       #$i++;
    }       
    return $s;
}

##############################################################
#
#
#             The same with regular expressions
#
#
#############################################################


my @str = @strs;
foreach my $s (@str) {
    print "'$s'\n";
    $s =~ s/^\s+//;
    print "'$s'\n";
    $s =~ s/\s+$//;
    print "'$s'\n";
    $s =~ s/\s+/ /g;
    print "'$s'\n";
    print "=======================\n";
}









More information about the Perl mailing list