SPUG: reg pattern matching in a loop

Noah Rømer klevin at eskimo.com
Fri Oct 14 16:01:19 PDT 2011


On 10/14/2011 12:35 PM, Ramon Hildreth wrote:

> open (OUTPUT, ">>$OUTPUTFILE");
> 
> while (<INPUT>)
> {
>         $_ =~ s/ \ +/|/;
>         print OUTPUT "$PRODUCTLINE $_";
> }

Well, there's nothing syntactically wrong with the above. However, it
may be more limited in effect than you're looking for. The above regex
will replace the first occurrence of two or more spaces on a line with a
single '|' character.

In order to replace all contiguous occurrences of the ' ' character with
a single '|', the regex would be

s/ +/|/g;

No backslash is needed, and the 'g' at the end tells Perl to not stop
after finding the first matching string on the line. If you don't want
to condense multiple spaces into a single '|' ('    ' -> '|'), but want
a '|' for each space char ('    ' -> '||||'), then the 'tr' command is
your friend

tr/ /|/;

This will replace every space found with a pipe character.

-- 
Noah Romer              | Character is easier kept than recovered.
klevin at eskimo.com       |
PGP key available       |
by finger or email      |


More information about the spug-list mailing list