substitute regex on arrays

Rob Nagler nagler at bivio.biz
Thu Oct 17 18:30:49 CDT 2002


John Evans writes:
> $s =~ s/^\s+//g;
> $s =~ s/\s+$//g;
> 
> I need to do this on an array of strings, but the best solution that I
> have is:
> 
> for ($cnt = 0; $cnt < @arr; ++$cnt) {
>   $arr[$cnt] =~ s/^\s+//g;
>   $arr[$cnt] =~ s/\s+$//g;
> }
> 
> 
> This works fine, but I'm wondering if there is a faster way of doing it?

Couple of things.  First, you want to use foreach in this context.
Second, one regex, is getter than two:

    foreach my $a (@arr) {
        $a =~ s/^\s+|\s+//g;
    }

You may want "m" on the end, to deal with multi-line strings.

Arrays are awkward sometimes.  Can you feed it into a whole string,
e.g.

    local($/);
    my($in) = <>;
    $in =~ s/^\s+|\s+//mg;

If you need to pass the string around, pass its reference.

Rob






More information about the Pikes-peak-pm mailing list